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?

From perldoc perlre:

   The numbered match variables ($1, $2, $3, etc.) and the related
   punctuation set ($+, $&, $`, $', and $^N) are all dynamically scoped
   until the end of the enclosing block or until the next successful match,
   whichever comes first.

In your first example, $1 is valid until the successful match /domain\.com/, 
when
it becomes undefined as there are no capturing parentheses. In the second 
example
$1 retains its value since the match fails.

It's always safer to save captured strings before you use them, and I would 
never
make a capture variable the target of a regex match as in your $2 !~ 
/domain\.com/.
Much better to write something like

 use strict;
 use warnings;

 my $email = '[EMAIL PROTECTED]';
 my ($name, $host) = $email =~ /(.*)@(.*)/;

 if ($host !~ /domain\.com/) {
   print "Host name is bad\n";
 }

 print "$name\n";

and also, in this case, the test would be better as

 unless ($host eq 'domain.com') {
   print "Host name is bad\n";
 }

unless you really want to test whether the host name /contains/ that string?

Oh, and I think I also prefer

 my ($name, $host) = split /@/, $email;

instead of the first regex.

HTH,

Rob


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


Reply via email to