•Re: = rather than =~ ?
by merlyn (Sage) on Jan 01, 2004 at 17:21 UTC
|
Good catch!
That should have been =~! Where were you when
that was being tech reviewed? Or where was my brain when I was typing that?
Thanks... I'll add it as an errata.
| [reply] |
|
This note might confuse newbies, so I thought just add a comment.
"That should have been =~!"
What merly said is that, that was a typo, and not what he wanted. (As you can see, he is the owner of that web page.)
But as a Perl statement, it is absolutely valid, and jweed has already given a full explanation.
| [reply] |
|
Goodness. And all this time I thought you had /meant/ it that way.
| [reply] |
Re: = rather than =~ ?
by jweed (Chaplain) on Jan 01, 2004 at 17:18 UTC
|
| [reply] |
Re: = rather than =~ ?
by Anonymous Monk on Jan 01, 2004 at 17:17 UTC
|
It depends.
I don't know what $input is, but that code is matching against $_.
If the match fails, the match fails.
Such code should always be written something like
$foo = $1 if /(foo)/;
| [reply] |
|
my $foo = m/(foo)/ ? $1 : '';
| [reply] [d/l] |
|
$foo = $1 if /(foo)/;
may be okay, but
my $foo = 1 if /(foo)/;
is not. | [reply] [d/l] [select] |
|
| [reply] |
|
|
|
|
Re: = rather than =~ ?
by SavannahLion (Pilgrim) on Jan 02, 2004 at 07:09 UTC
|
I just wanted to say thank you for pointing something like that that is so fundamentally important. After reading your example and better understanding how $1 behaved, I went back and took a careful look over some source code. There were three distinct sections where I made that error. After I examined the code logic, there was indeed one circumstance where, if the match failed, then there was a potential for $1 to be exposed. (The other two are wrapped in if statements.)
Fortunately, I took to reading PerlMonks on a regular basis and happened to read this post before the code went, "live." There's no way I can give all of my daily allocated points to just the people in this thread, but if I could, I would.
----
Thanks for your patience.
Prove your knowledge @ HLPD
Edit: Fixed botched HTML :) Sorry everyone has a different markup language.
| [reply] |
Re: = rather than =~ ?
by inman (Curate) on Jan 02, 2004 at 18:04 UTC
|
Another potentially confusing variation would be if list context was used since the match will return the list of matched sub-expressions. In the example below, $input is assigned a value for each iteration wheras $1 is only changed on a good match.
#! /usr/bin/perl
use strict;
my $input;
while (<DATA>)
{
($input) = /(\w+)/;
print "\$input=$input\t\$1=$1\n";
}
__DATA__
Hello
World
Output:
$input=Hello $1=Hello
$input= $1=Hello
$input=World $1=World
| [reply] [d/l] [select] |