Bret Hughes | 1 Dec 2006 15:05

Re: Perl help


Todd A. Jacobs wrote:
> On Thu, Nov 30, 2006 at 07:57:49PM -0600, Bret Hughes wrote:
>
>   
>> Won't the variables be overwritten with an empty string except for the
>> last line of the data assuming it matched?  I'll play abit and then
>> ask why is does not.
>>     
>
> Despite what Charles said, I *do* think they'd get overwritten if you
> were using the match operator to return a value. See here:
>
>     # Returns "oo" which is the value of the matching subexpression.
>     perl -e '
> 	    $a = "foo"; 
> 	    ($b) = ($a =~ m/(oo)/); 
> 	    print "$b\n"
>     '
>
>     # Returns nothing, because the second match returns an empty string
>     # and overwrites the first.
>     perl -e '
> 	    $a = "foo"; 
> 	    ($b) = ($a =~ m/(oo)/); 
> 	    ($b) = ($a =~ m/(aa)/); 
> 	    print "$b\n"
>     '
>
> And to answer my previous question, this returns entirely the wrong
> thing:
>
>    # Returns "1" which is the result code for the m// operator.
>     perl -e '
>             $a = "foo";
>             $b = ($a =~ m/(oo)/);
>             print "$b\n"
>     '
>
> probably because $b isn't being evaluated in a list context, but I don't
> know perl well enough to know *why* it does the wrong thing (by my
> lights) here.
>
> As for your example, all it will do is return boolean truth for each
> line where a match is found, and nothing otherwise. For a quick a dirty
> test of this, try this one-liner:
>
>     perl -ne '$a = /root/ && print $a."\n";' /etc/passwd
>
> Perl wonks will tell you perl always tries to "do the right thing," but
> I sure think that depends a lot on whether you agree with perl's idea of
> what's right. :)
>
>   

Yes I believe that you are right about over writing the values. As for 
returning the value there apears to be a couple of things happening 
first, you need some parens to tell match what to return, but that was 
not enough the issue seems to be the &&
this works for me:

[bhughes <at> tulfw1 bhughes]$ perl -ne '($a) = /(root)/;if ($a){ print 
$a."\n";}' /etc/passwd
root
root

this did not

perl -ne '($a) = /(root)/ && print $a."\n";' /etc/passwd

I did get two blank lines so I surmised that the operator precedence 
between && and = was this issue.  Here it is using and:

 perl -ne '($a) = /(root)/ and print $a."\n";' /etc/passwd
root
root

Huh. 

Bret

Gmane