in reply to passing an array
Notice the sub call:use warnings; use strict; sub multipop(\@$); my @array = (1 .. 10); my @result = multipop @array, 3; print "@array\n"; print "@result\n"; sub multipop(\@$) { my $count = pop; my @vars; $count = 1 if ! defined $count; # default to normal pop behavior if ( $count =~ /^\d+$/ ) { my $length = scalar @{$_[0]}; $count = $length if $count > $length; # Using @{$_[0]} to ensure that we modify original array push @vars, splice ( @{$_[0]}, -$count, $count ) if $count > 0 +; return @vars; } else { warn "Second argument to multipop must be numeric: '$count'"; } }
Yup, you're passing an array to it, but Perl converts it to a reference to the array. Pretty handy, huh? You may want to read this discussion of prototypes and their limitationsmy @result = multipop @array, 3;
And yeah, that code above is a bit of a hack. If anyone sees problems with it, I'd love to know. It's basically the same thing as pop, but with an optional second argument specifying the number of elements to remove. It could be expanded to take a third argument specifying if the order of elements to remove is to be reversed. It does have a couple of advantages over splice (IMHO): it's easier to read and will not die if you try to pop more elements than the array has. Of course, some may not appreciate the latter "feature".
Oh, and it's slower than splice, too :)
Cheers,
Ovid
Update: Ugh! Stupid me. No third argument. Just make the second one negative for a reverse pop (and add the appropriate code, of course). Sheesh. I try to make things too hard, at times :)
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (Ovid - prototypes?) Re: passing an array
by agoth (Chaplain) on Mar 28, 2001 at 12:23 UTC |