|We don't bite newbies here... much|
Re: What are multiple $_ =~ operations doing?by davido (Cardinal)
|on Apr 01, 2005 at 09:44 UTC||Need Help??|
Let me answer your last question first.
The =~ binding operator binds the scalar on its left with the regexp (or transliteration) operator on the right, so that the regexp operator may examine and act upon the scalar on the left.
The = assignment operator assigns the value of the expression on the right hand side to the variable on the left.
The == equality operator evaluates the numeric equality of the items to its left and right. It has nothing to do with assignment.
Now for your first question:
$_ is a sort of alias to the first argument passed to the enclosing subroutine. In fact, perlsyn states, "The array @_ is a local array, but its elements are aliases for the actual scalar parameters." As the documentation also states, modifying $_ will attempt to modify the value held in the variable passed in the sub's arg list. For example:
As you can see, incrementing $_ increments $value too (because they're basically the same thing).
Now as the docs say, if you attempt to modify the value of an unmodifiable scalar, you get an error. For example:
If you run this, you'll get an error. This is because $_ is aliased to a value, not a variable, in this case, and you can't change a hard-coded value. 100 cannot be 101 :)
As a matter of maintainable style, it's often discouraged to allow your subroutines to modify the values of their parameters. But as with most things Perlish, this rule of thumb only applies where convenient. After all, chomp modifies its parameter list. So does chop.
I hope this helps.