网上教程
http://man.ddvip.com/web/perl/index.htm
The Binding Operator
When you do a pattern match, you need three things:
-
the text you are searching through
-
the pattern you are looking for
-
a way of linking the pattern with the searched text
As a simple example, let's say you want to see whether a string variable has the value of "success". Here's how you could write the problem in Perl:
$word = "success"; if ( $word =~ m/success/ ) { print "Found success\n"; } else { print "Did not find success\n"; }
There are two things to note here.
First, the "=~" construct, called the binding operator, is what binds the string being searched with the pattern that specifies the search. The binding operator links these two together and causes the search to take place.
Next, the "m/success/" construct is the matching operator, m//, in action. The "m" stands for matching to make it easy to remember. The slash characters here are the "delimiters". They surround the specified pattern. In m/success/, the matching operator is looking for a match of the letter sequence: success.
Generally, the value of the matching statement returns 1 if there was a match, and 0 if there wasn't. In this example, the pattern matches so the returned value is 1, which is a true value for the if statement, so the string "Found success\n" is printed.
+++++++++++++++++++++++++++++++++++++++++
$_ the default variable of Perl
There is a strange scalar variable called $_ in Perl, which is the default variable, or in other words the topic.
In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used. In general, I'd say you should NOT see $_ in real code. I think the whole point of $_ is that you don't have to write it explicitly.
Well, except when you do.
Having a default variable is a very powerful idea, but using it incorrectly can reduce the readability of your code.
Check out this script:
use strict; use warnings; use v5.10; while (<STDIN>) { chomp; if (/MATCH/) { say; } }
This is exactly the same as:
use strict; use warnings; use v5.10; while ($_ = <STDIN>) { chomp $_; if ($_ =~ /MATCH/) { say $_; } }
I would never write the second one, and I'd probably write the first one only in a very small script, or in a very tight part of the code.
Maybe not even there.
As you can see, in a while loop, when you read from a file handle, even if that's the standard input, if you don't assign it explicitly to any variable, the line that was read will be assigned to $_.
chomp() defaults to work on this variable, if no parameter was given.
Regular expression matching can be written without an explicit string, and even without the =~ operator. If written that way, it will work on the content of $_.
Finally say(), just as print(), would print the content of $_, if no other parameter was given.