2009/11/11 Uri Guttman <u...@stemsystems.com>:
>>>>>> "PP" == Philip Potter <philip.g.pot...@gmail.com> writes:
>
>  PP>     my %readfsgs_flags;
>  PP>     my @flags_to_copy = qw(limit); # can scale up by adding more hash 
> keys here
>  PP>     @readfsgs_fla...@flags_to_copy} = @{$flag...@flags_to_copy};
>  PP>     my @results = readfsgs($testfilename, \%readfsgs_flags);
>  PP> }
>
>  PP> but this has a bug: if $flags doesn't contain limit, %readfsgs_flags
>  PP> will contain (limit => undef); ie $readfsgs_flags will exist but be
>  PP> undefined. It shouldn't exist.
>
> easy fix. just grep through all the keys you want and test for exists.
>
>
> my @flags_to_copy = grep { exists( $flags->{$_} } qw(limit);
>
> then the slice works as you have it and you only get flags you are
> interested in and also that exists coming in.

That fixes the major problem, thanks!

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

Is this really simpler than my version?
>  PP>     @readfsgs_fla...@flags_to_copy} = @{$flag...@flags_to_copy};

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

Also, is the hash ref necessary? Would this also work?
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) ;

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

Phil

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to