RE: Safe list assignment
[email protected] ("Ed Avis")
| Newsgroups | perl.beginners |
|---|---|
| Message-ID | <[email protected]> |
Chas. Owens wrote:
>>safe_assign ($a, $b, $c) = @array; # will die if scalar(@array) != 3
>
>Not that I am aware of, but it is a breeze to build one:
[code snipped]
That doesn't quite work - try testing it with
my @a = (1 .. 3);
my ($a, $b, $c);
safe_assign [ $a, $b, $c ], @a;
say foreach $a, $b, $c;
You'd need to make a version taking references, so it would look like
safe_assign_b [ \($a, $b, $c) ], @a;
or alternatively, write a version that modifies its parameters directly and takes the RHS as a list reference:
sub safe_assign_c {
croak 'usage: safe_assign_c LHS, ..., RHS-listref' if @_ < 2;
my @rhs = @{pop @_};
croak 'wrong number of elements in RHS' if @_ != @rhs;
foreach (@_) {
$_ = shift @rhs;
}
}
my @a = (1 .. 3);
my ($a, $b, $c);
safe_assign_c $a, $b, $c, \@a;
say foreach $a, $b, $c;
And then this sort of thing could be generalized somehow to make safe versions of assignments like
my ($first, $second, @rest) = @a;
where clearly @a should have two or more elements.
But my question is, is there a standard way to do this? Like a CPAN module that provides a concise and clear syntax to do safe list assignments. It seems like it should be a pretty common operation. Ideally, 'use warnings' would give a runtime warning when the LHS and RHS don't match up.
If there isn't a consensus on the recommended way to do this (in the same way that Carp is the recommended way to give error messages, File::Slurp is the recommended way to read a whole file, etc) then I may try to make one.
--
Ed Avis <[email protected]>
______________________________________________________________________
This email has been scanned by the MessageLabs Email Security System.
For more information please visit http://www.messagelabs.com/email
______________________________________________________________________