develooper Front page | perl.perl5.porters | Postings from April 2008

[perl #51394] String processing error (concatonation+regexp)

From:
Animator via RT
Date:
April 27, 2008 05:30
Subject:
[perl #51394] String processing error (concatonation+regexp)
Message ID:
rt-3.6.HEAD-23612-1209213227-334.51394-14-0@perl.org
> -----------------------------------------------------------------
> [Please enter your report here]
> 
> Code sample:
> 
> $a='hi';
> $b='boo';
> 
> if($a.$b =~ /red/) { print "Misidentified string - bug found!\n"; }
> else { print "All okay\n"; }
> 
> [Please do not change anything below this line]
> -----------------------------------------------------------------

Hello,


First of all thank you for your bug report.

But this is not a bug.
If you look at the 'Operator Precedence and Associativity' list in 
perldoc perlop then you see that the binding operator (=~) is listed 
before the concatenation operator (.).

This means that Perl parses your code as:

if ($a . ($b =~ /red/)) { }

So it contatentates $a ('hi') with ($b =~ /red/) ('').

So the if statement you wrote really is: if ('hi') { ... }

A way to come to this conclusion is to use print.

print ($a . ($b =~ /red/)); # ==> will print 'hi'.

To make it work like you want you need to tell Perl that $a.$b should 
have an higher precedence then =~ (by placing it between ()).

print (($a . $b) =~ /red/); # ==> will print the empty string ''.


Kind regrads,

Bram




nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About