Cool/useful short examples of Perl?
David Matthewman
david at matthewman.org
Wed Jun 8 14:27:51 BST 2011
On 8 Jun 2011, at 13:41, Paul Makepeace wrote:
> On Wed, Jun 8, 2011 at 13:17, Tom Hukins <tom at eborcom.com> 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) { ... }
>>
>> It's sunny outside and pubs are open: I can think of worse times to
>> lose my job.
>>
>>> Or does everyone think they are always equivalent?
>>
>> I'm not everyone, and with a language as flexible as Perl I hesitate
>> to make strong statements involving words like "always", but I don't
>> recall encountering a situation where they differ.
>
> $ perl -le 'print "$_ == !!$_ ? ", $_ == !!$_ ? "yes" : "no" for (-1,
> 0, 1, 2, undef)'
> -1 == !!-1 ? no
> 0 == !!0 ? yes
> 1 == !!1 ? yes
> 2 == !!2 ? no
> == !! ? yes
Well, -1 may not equal !!-1, but truthwise it's the same, so it's the same to an if or unless statement.
I realise this is getting a bit silly, but:
foreach my $test_item (-1, 0, 1, 2, undef, '') {
print "$test_item:\t"
. return_truth_by_if_not($test_item) . ', '
. return_truth_by_unless($test_item) . ', '
. return_truth_by_if_not(!$test_item) . ', '
. return_truth_by_unless(!$test_item) . ', '
. return_truth_by_if_not(!!$test_item) . ', '
. return_truth_by_unless(!!$test_item) . "\n";
}
sub return_truth_by_if_not {
my $value = shift;
if (!$value) {
return 'non';
}
else {
return 'oui';
}
}
sub return_truth_by_unless {
my $value = shift;
unless ($value) {
return 'non';
}
else {
return 'oui';
}
}
--
David Matthewman
More information about the london.pm
mailing list