princepawn has asked for the wisdom of the Perl Monks concerning the following question:

What is the functional difference between the $_ = line and the $_ =~ line line of code? Besides one being commented out... hahahah very funny :) The latter is a patch that I got that he was happy with and it passes my test case, so I never bothered about it, but now I have some free time and was wondering what the diff was in the 2 lines.
foreach (@{$dir}) { # $_ =~ m#([a-z-]*)\s*([0-9]*)\s*([0-9a-zA-Z]*)\s*([0-9a-zA-Z] +*)\s*([0-9]*)\s*([A-Za-z]*)\s*([0-9]*)\s*([0-9A-Za-z:]*)\s*([A-Za-z0- +9.-]*)#; $_ = m#([a-z-]*)\s*([0-9]*)\s*([0-9a-zA-Z]*)\s*([0-9a-zA-Z] +*)\s*([0-9]*)\s*([A-Za-z]*)\s*([0-9]*)\s*([0-9A-Za-z:]*)\s*([\w*\W*\s +*\S*]*)#; my $perm = $1; my $inode = $2; my $owner = $3; my $group = $4; my $size = $5; my $month = $6; my $day = $7; my $yearOrTime = $8; my $name = $9; my $linkTarget;

Carter's compass: I know I'm on the right track when by deleting something, I'm adding functionality... download and use The Emacs Code Browser

Replies are listed 'Best First'.
Re: [perlre] $_ = /$re/ vs $_ =~ /$re/
by MarkM (Curate) on Aug 28, 2003 at 23:49 UTC

    Note that "$_ = /$re/" is actually equivalent to "$_ = ($_ =~ /$re/)". The final result that I would expect, is for ($_ =~ /$re/) to be interpretted in scalar context, resulting in a boolean value (1 or ""), and for the boolean value to be assigned to $_, which will alter the elements in @$dir to each be either 1 or "", depending on whether the element matched the regular expression or not.

    Since you don't seem to be using @$dir again, this may have gone unnoticed. Since both expression invoke '$_ =~ /$re/', they do indeed 'do the same thing'.

    If you are trying to reduce characters, try just "/$re/" without any mention of $_. As others recommended, you should really use "if (/$re/) {", as the match may not succeed.

Re: [perlre] $_ = /$re/ vs $_ =~ /$re/
by revdiablo (Prior) on Aug 29, 2003 at 01:50 UTC

    MarkM has directly answered your question, but I thought it might be handy to point out that m/// m// in list context returns all the subexpressions matched in parens. I think this would be useful in your example code. e.g.:

    my ($perm, $inode, $owner, $group, $size, $month, $day, $yearOrTime, $name) = m!$re_with_capturing_parens! or next;

    Note: the or next at the end of this satisfies the recommendation to skip any lines that don't match.

    Update: make that m// instead of m/// :-)

Re: [perlre] $_ = /$re/ vs $_ =~ /$re/
by runrig (Abbot) on Aug 28, 2003 at 23:41 UTC
    The first just calls the match operator on $_, and the second version does the same and then sets $_ to the empty string or 1. Either way, there really should be a test to see if the match is successful before you go using the $1, $2, etc. variables.