My only point was regarding when you simply want to return a false
value to indicate a subroutine failure. Consider the following
contrived example where we only want to process strings beginning
with a particular pattern:
#!/usr/bin/perl -w
use strict;
my @patterns = (qr/^foo/, qr/^qux/);
my @strings = ('foo bar', 'bar bar', 'qux bar');
my @stuff;
foreach my $string (@strings){
if(@stuff = dice_it($string)){
print "Processing: $string\n";
process_stuff(@stuff);
}
}
sub dice_it {
my $string = shift;
foreach my $pat (@patterns) {
return split //, $string if $string =~ /$pat/;
}
return undef;
}
sub process_stuff {
foreach (@_) {
print "<$_>";
}
print "\n";
}
I'm not suggesting this a terribly common problem (or that the above
is a good way to approach this particular example). I just wanted to
point out that returning 'undef' as a failure mode isn't always
appropriate -- and people who do so may forget that an array
containing one undefined element still evaluates to true so they may
bang their head for a while before they realize why they are
processing the string 'bar bar' and getting a warning. Changing the
last line of dice_it() to just a bare 'return' statement alleviates
the problem because it returns the 'right' thing depending on context.
|