in reply to Re: sort in array of hash required
in thread sort in array of hash required

To print out the data:
print "#keynum, keyname, name\n"; print "$_->{'keynum'}, $_->{'keyname'}, $_->{'name'}\n" for @sortedAna +me;
How could I optimize the repetitive $_->{'<key>'} structure?

Have a nice day, j

Replies are listed 'Best First'.
Re^3: sort in array of hash required
by johngg (Canon) on Nov 16, 2011 at 16:37 UTC

    Use a hash slice.

    knoppix@Microknoppix:~$ perl -E ' > @arr = ( > { > keynum => 50, > keyname => q{fruit}, > name => q{plum}, > }, > { > keynum => 100, > keyname => q{fish}, > name => q{cod}, > }, > { > keynum => 200, > keyname => q{fowl}, > name => q{duck}, > }, > ); > printf qq{%10s%10s%10s\n}, qw{ #keynum keyname name }; > printf qq{%10d%10s%10s\n}, @$_{ qw{ keynum keyname name } } > for @arr;' #keynum keyname name 50 fruit plum 100 fish cod 200 fowl duck knoppix@Microknoppix:~$

    I hope this is helpful.

    Cheers,

    JohnGG

Re^3: sort in array of hash required
by AnomalousMonk (Archbishop) on Nov 16, 2011 at 17:04 UTC
    How could I optimize ...

    Note that johngg's approach of Re^3: sort in array of hash required is not an 'optimization' in the sense of execution speed; I doubt it would run significantly, if at all, faster.

    However, it offers, IMHO, potential significant advantages in terms of maintainability. E.g., the group of keys  keynum keyname name can be factored out (if you could get rid of that pesky '#' that's buzzing around in there) into an array definition (possibly made a constant) and used in many places without concern for having 'forgotten something'. If it becomes necessary to change anything about this group of keys, it is only necessary to do so in one place.