in reply to WARNING!! Possible Brainbench spoilers (do NOT read unless you've taken and passed the cert)
Context, my friend...
$ perl my $data = "Hello World" =~ /(.*) (.*)/; print "$data\n"; ^D 1
$ perl my ($data) = "Hello World" =~ /(.*) (.*)/; print "$data\n"; ^D Hello
The first example is a scalar assignment ; $data is assigned the value of "Hello World" =~ /(.*) (.*)/ in scalar context, which is "true", by convention "1". The second example is a list assignment ; $data is assigned the string captured by the first capturing paren, that is, "Hello".
See the documentation on m// in perldoc perlop.
P.S. ++dragonchild for my $nmatches = () = $stuff =~ m/.../; Now one might ask: why m// doesn't return the number of matches in scalar context in the first place? I think the reason lies with the /g modifier which behaves differently in scalar and list contex. Also, for capturing parens, the "number of matches" is constant (it's really all or none), so the designers of the language decided to stay consistent and return "1" in all situations. Any more insight?
Update: Fixed small error in code
|
|---|