At 11:07 AM 5/3/2006, David Kaufman wrote:
Hi Chris,
Chris Wagner <[EMAIL PROTECTED]> wrote:
> At 01:28 AM 5/3/2006 -0400, David Kaufman wrote:
>> my ($b, $c) = ($1, $2) if $a =~ /^(\D+)(\d+)/;
>
> U can't combine a my and an if. Perl will go schizo.
Sure "U" can :-) I use this type of construct all the time, even
with strict mode and warnings on. What you mean by "perl will go schizo"?
What *will* happen is that, if $a doesn't match the regex, $b and $c
will be undefined. But I use this in cases, like the original
poster's, where the regex is expected to always match. In such
cases an error has already occurred so any subsequent "Use of
uninitialized value" warnings will warn me that the string contained
something it was never supposed to contain.
That's what you would think. I.e., in the simple statement:
my $val = <expr1> if <expr2>;
you would think that if <expr2> were false, that certainly $val would
end up undefined. Alas, that is not the case. There is absolutely no
guarantee about the value of $val after this statement is executed
when <expr2> is false. In my opinion, this is a genuine Perl bug -
however, not everyone would agree with me. Check out the code below.
Note that I use both 'strict' and 'warnings'. The function f() takes
a character and returns its ordinal value. However, it uses the hash
$h as a cache, so that when you call f(), it first checks to see if
it has previously encountered the character you passed it, in which
case it returns the value that it previously saved there. (Never mind
that the ord() function is so fast that caching the ordinal value of
a character to save processing time doesn't really make sense here).
The point is that the first time f() is called, it computes ord('x'),
which is 120, and stores that in $h. But, the next time f() is
called, this time with a different value 'y', when the line marked
'HERE' is executed, the condition $h->{$ch} fails, but $val, instead
of being undefined, has the value it had during the previous call to
f(), i.e. 120. So, it returns that. Trust me, it took me a long time
to find this problem in a much more complex piece of code. Bottom
line is, never combine 'my' with a trailing 'if'.
use strict;
use warnings;
our $h = {};
print("f(x) = ", f('x'), "\n");
print("f(y) = ", f('y'), "\n");
sub f {
my $ch = shift;
my $val = $h->{$ch} if $h->{$ch}; # HERE
if ($val) {
return $val;
}
else {
$val = ord($ch);
$h->{$ch} = $val;
return $val;
}
} # f()
_______________________________________________
Perl-Win32-Users mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs