perl.beginners
[Top] [All Lists]

Re: hash keys and readable code

Subject: Re: hash keys and readable code
From: Uri Guttman
Date: Wed, 11 Nov 2009 13:38:26 -0500
Newsgroups: perl.beginners

>>>>> "PP" == Philip Potter <philip.g.potter@xxxxxxxxx> writes:

  PP> 2009/11/11 Uri Guttman <uri@xxxxxxxxxxxxxxx>:

  >> you can also simplify the copy a little with a hash ref:
  >> 
  >> my $readfsgs_flags = { map { $_ => $flags->{$_} } @flags_to_copy } ;

  PP> Is this really simpler than my version?
  PP> @readfsgs_flags{@flags_to_copy} = @{$flags}{@flags_to_copy};

one less line to declare the hash as mine is a hash ref. fewer lines is
generally simpler (not alway!). also more people get map than slices (i
use them both all the time).

  PP> It took me a while to parse the map call, and the extra curlies from
  PP> the anonymous hash get confused with the code block curlies. Is this
  PP> map call a common technique for constructing subhashes (analogous to
  PP> subsets)?

sure. maps can generate any list from an input list. what is different
about a list of key/values to populate a hash? if you don't like the
hash ref style, assign the map to a hash itself:

my %readfsgs_flags = map { $_ => $flags->{$_} } @flags_to_copy ;

i just like the ref style as i don't need to use \%readfsgs_flags to
pass it down the line.

  PP> Also, is the hash ref necessary? Would this also work?
  PP> my %readfsgs_flags = map { $_ => $flags->{$_} } @flags_to_copy;

  >> and if you feel like really combining lines (not so great in this case):
  >> 
  >> my $readfsgs_flags = { map { $_ => $flags->{$_} }
  >>        grep { exists( $flags->{$_} } qw(limit) ;
  >> 
  >> 
  >> or another cleaner way would be to put the exists inside the map:
  >> 
  >> my $readfsgs_flags = {
  >>        map { ( exists( $flags->{$_} ) ? $_ => $flags->{$_} : () } 
qw(limit) ;

  PP> I see what you've done there. I think you're right that it's probably
  PP> best in two statements -- after all, it's going to be two lines
  PP> whether it's two statements or one.

sure. i was just showing how to combine lines like that. sometimes there
is a decent win, other times it gets too noisy.

uri

-- 
Uri Guttman  ------  uri@xxxxxxxxxxxxxxx  --------  http://www.sysarch.com --
-----  Perl Code Review , Architecture, Development, Training, Support ------
---------  Gourmet Hot Cocoa Mix  ----  http://bestfriendscocoa.com ---------

<Prev in Thread] Current Thread [Next in Thread>