请解释语法

时间:2012-06-25 17:42:01

标签: perl syntax

我正在寻求帮助来解释以下语法。我检查了我的Perl书,并在网上查了一下。

我正在寻找以下内容:

$option =~ s/\s+//g
$option =~ m/^\s*$

非常感谢。

2 个答案:

答案 0 :(得分:5)

sm是将regular expressions应用于字符串的运算符。 s///是替换运算符,m//是匹配运算符。他们都把正则表达式作为他们的第一个论点(在//内)。 =~告诉Perl使用/匹配正则表达式$option。有关详细信息,请参阅perlre

以下是这些正则表达式的作用:

use warnings;
use strict;
use YAPE::Regex::Explain;
print YAPE::Regex::Explain->new( qr/\s+/ )->explain;

The regular expression:

(?-imsx:\s+)
matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

简而言之:它取代了具有多个空格字符的每个实例,并且没有任何内容。

print YAPE::Regex::Explain->new( qr/^\s*$/ )->explain;

正则表达式:

(?-imsx:^\s*$)

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  \s*                      whitespace (\n, \r, \t, \f, and " ") (0 or
                           more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------

如果字符串仅包含空格字符,那么匹配。尽可能多,但至少为零,没有别的。

答案 1 :(得分:3)

嗯,第一个表达式是s(ubstitution),它查找一个或多个空格并将其删除。 +指定一个或多个空格(\s)字符。

第二个看起来是m(atch)一个空行。 ^锚点与行的开头匹配,$到达终点。因此,只有包含零个或多个(即*)个空格的行才能成功匹配。

这两个表达式都对$option变量起作用,因为=~将它们绑定到它。

相关问题