On 05/12/2007 09:21 AM, Steve Bertrand wrote:
I have two scenarios here, and in the first one, I am not seeing the logic I would normally expect. I'll compact the code as to save everyone from scrolling. I have strict and warnings enabled (as I always do). Can someone tell me why in the first case $1 isn't initialized and in the second case it is?


# First run(catch $1 and $2, check $2 for correctness (it is), print $1)

my $email = '[EMAIL PROTECTED]';
$email =~ /(.*)@(.*)/;
if ($2 !~ /domain\.com/) {
        print "var 2 is bad\n";
}
print "$1\n";

/** prints 'uninitialized' for line 'print "$1\n";**/


# Second run(same as above, but the if will fail:

my $email = '[EMAIL PROTECTED]';
$email =~ /(.*)@(.*)/;
if ($2 !~ /domain\.com/) {
        print "var 2 is bad\n";
}
print "$1\n";

/** prints
var 2 is bad
steveb
*/

Why does the $1 initialize and print only if the 'if' fails?

TIA,

Steve


That happens because the match variables ($1, $2, ...) are only changed when a regular expression matches; otherwise, they are left alone.

In the first case, "$2 !~ /domain\.com/" succeeds but does not capture anything, so the numbered match variables are unset.

Your situation reinforces the rule that you should always test if the match succeeded before you attempt to use the match variables:

    my $email = '[EMAIL PROTECTED]';
    my @f = (undef, $email =~ /(.*)\@(.*)/);

    (@f > 1) && ($f[2] =~ /domain\.com/ ?
        print "$f[1]\n" : print "var 2 is bad\n" );

The test "@f > 1" is my way of testing if the match succeeded.

HTH




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to