[Chicago-talk] my my if nothing

Jim Thomason jthomasoniii at yahoo.com
Wed May 5 10:15:59 CDT 2004


This was touched upon last night at the talk, and I
didn't quite remember the details. I was actually
closer than I thought.

What was mentioned (and that I directed things to) was
the case of doing this:

  my $variable = 'foo' if 0;

To generalize it. The specific case was a regex:

  my $filename = $1 if $directory =~ s!([^/]+)$!!;

And the issue is that the regex may fail (though in
this case it was actually guaranteed to succeed) and
that bizarre things can result.

The general case is that this construct can be used
(among other things) to simulate a static variable if
you don't want to use a closure. 

Basically, the variable gets lexicalized on the first
pass, but never again. Further, the assignment fails.

Here, observe:

foreach (1..5) {
   my $i = 7;
   print $i++, "\n";
}

7
7
7
7
7

foreach (1..5) {
  my $i = 7 if 0;
  print $i++, "\n";
}

0
1
2
3
4

(incidentally, $i starts off as undefined, it only
prints out 0 because the ++ vivified it into that)

This is a "feature" that has been flagged as something
that might go away in the future. It's still around in
my 5.8.4, though, so it hasn't vanished yet.

Personally, I avoid it like the plague, but it's
another one of those useful things to be aware of in
case you encounter it.

-Jim....


	
		
__________________________________
Do you Yahoo!?
Win a $20,000 Career Makeover at Yahoo! HotJobs  
http://hotjobs.sweepstakes.yahoo.com/careermakeover 



More information about the Chicago-talk mailing list