Re: Safe list assignment
[email protected] ("Dr.Ruud")
| Newsgroups | perl.beginners |
|---|---|
| Organization | Chaos rules. |
| Message-ID | <[email protected]> |
Ed Avis schreef:
> Perl's list assignment feature is very useful.
>
> sub returns_three_things { return (1, 2, 3) }
> my ($x, $y, $z) = returns_three_things();
>
> Often, though, you want to add some error checking. Particularly
> when providing an interface that others can call.
>
> # Parameters: first name, last name, birthday.
> sub print_person_details {
> croak 'pass three arguments' if @_ != 3;
> my ($first_name, $last_name, $birthday) = @_;
> say "$first_name $last_name was born on $birthday";
> }
>
> The extra 'croak' test gives a more friendly error message than 'use
> of uninitialized value in ...', which would require the user of the
> subroutine to go digging in its code to find what he passed wrongly.
>
> Even in code that's not part of a public interface, you may want to
> check that the list has the right size before you do the assignment,
> just to catch programmer mistakes early rather than waiting for an
> uninitialized value warning later on.
>
> But it's rather a pain to keep checking the list size each time.
> When you 'unpack a tuple' in Python the size is checked and an
> exception is thrown if it's too big or too small. Is there an
> equivalent in Perl? Something like
>
> safe_assign ($a, $b, $c) = @array; # will die if
> scalar(@array) != 3
Even if the number of parameters is right, the values of the parameters
might be wrong. So you beter check each value.
perl -we'
sub say { return print $_[0], qq{\n} }
sub print_person_details {
defined or return for @_[0..2];
return say qq{$_[0] $_[1] was born on $_[2].};
}
print_person_details qw{John Johnson Friday afternoon}
or say q{error};
print_person_details qw{Eve Evening}
or say q{error};
'
John Johnson was born on Friday.
error
--
Affijn, Ruud
"Gewoon is een tijger."