Perl Question: pop sort keys %hash
Matt Diephouse
matt at diephouse.com
Wed Oct 8 17:29:10 CDT 2003
I already emailed Ed, but realized I didn't send a copy to the group,
so I thought I'd give this another go.
The reason perl gives that warning is that sort *does not* return an
array. Perl actually has both arrays and lists. Here it returns a list,
meaning that you can't use pop, which is just for arrays.
You can access the last element of a list though, using an index:
#!/usr/bin/perl -w
use strict;
my %hash = (
abc => 1,
xyz => 2
);
my $last_key = (sort keys %hash)[-1];
Hope this helps,
matt
On Wednesday, October 8, 2003, at 11:20 AM, Ed Eddington wrote:
> A quick Perl oddity... I tried to grab the last element of a sorted
> list of hash keys in a quick one liner, but was forced to use an array
> variable. Anybody know why I can't do this? Sort *does* return an
> array, but pop complains at compile time that its argument isn't an
> array variable...
>
> "Type of arg 1 to pop must be array (not sort)"
>
> I tried messing with parens and other bracketry to no avail. Just
> curious if anyone can explain this.
>
> Ed
>
> ---------------
> #!/bin/perl
>
> my %hash;
> $hash{abc}='1';
> $hash{xyz}='2';
>
> #my $lastkey = pop sort keys %hash; # this doesn't work.
>
> my @sorted = sort keys %hash; # this works using an extra
> step
> my $lastkey = pop @sorted;
>
> print "last hash key is $lastkey\n";
More information about the grand-rapids-pm-list
mailing list