Cool/useful short examples of Perl?

David Landgren david at landgren.net
Thu Jun 9 12:10:37 BST 2011


On 08/06/2011 15:00, David Matthewman wrote:
>
> On 8 Jun 2011, at 13:17, Tom Hukins wrote:
>
>> On Wed, Jun 08, 2011 at 02:00:41PM +0200, Abigail wrote:
>>> I'd rather go for sacking people that don't know the difference
>>> between
>>>
>>>     if (something) { ... }
>>>
>>> and
>>>
>>>     unless (!something) { ... }
>>

[...]

> Their side effects are different. There may be a simpler way to demonstrate this, but for instance:

I still don't get it. Abigail wasn't talking about !!. Your code seemed 
to be more to the point, and so I fleshed it out. Consider:

#! /usr/bin/env perl -l

foreach my $var (-1, 0, '0 but true', 1, 2, "0", '', ' ', undef) {
     print "\n", defined $var ? $var : 'undef';
     is_if($var);
     not_unless($var);
     not_if($var);
     is_unless($var);
}

sub is_unless {
   unless ($_[0]) {
     print +(caller 0)[3];
   }
}

sub is_if {
   if ($_[0]) {
     print +(caller 0)[3];
   }
}

sub not_unless {
   unless (!$_[0]) {
     print +(caller 0)[3];
   }
}

sub not_if {
   if (!$_[0]) {
     print +(caller 0)[3];
   }
}

__END__

This produces:

-1
main::is_if
main::not_unless

0
main::not_if
main::is_unless

0 but true
main::is_if
main::not_unless

1
main::is_if
main::not_unless

2
main::is_if
main::not_unless

0
main::not_if
main::is_unless


main::not_if
main::is_unless


main::is_if
main::not_unless

undef
main::not_if
main::is_unless

Which leads me to conclude that you enter a block whether you write if 
($foo) or unless (!$foo) (which I was glad to observe, otherwise my sky 
would be falling down). So I can't see the side effects to which Abigail 
alludes.

David

--
There's bum trash in my hall and my place is ripped
I've totalled another amp, I'm calling in sick


More information about the london.pm mailing list