Hi all, I have a subroutine which uses a hashref to accept optional parameters:
sub do_test { my ($testfilename, $flags) = @_; ## etc... } Here $flags is given an hashref containing optional arguments such as { thorough => 1, limit => 3, retries => 2}. One (but not all) of the flags is, if present, passed on to a downstream subroutine. So I've got code something like this: sub do_test { my ($testfilename, $flags) = @_; my @results = exists $flags->{limit} ? readfsgs($testfilename, {limit => $flags->{limit} }) : readfsgs($testfilename, { } ); } where readfsgs needs the 'limit' entry but not the others from $flags. I was wondering if maybe its better to build the optional argument hashref first to simplify the call: sub do_test { my ($testfilename, $flags) = @_; my %readfsgs_flags; $readfsgs_flags{limit} = $flags->{limit} if exists $flags->{limit}; my @results = readfsgs($testfilename, \%readfsgs_flags); } but the extra exists test seems a bit ugly and it won't scale up well if I have a few flags to transfer to the child subroutine. The first version will not scale up either. To make it more scalable, I thought about doing it using hash slices: sub do_test { my ($testfilename, $flags) = @_; my %readfsgs_flags; my @flags_to_copy = qw(limit); # can scale up by adding more hash keys here @readfsgs_fla...@flags_to_copy} = @{$flag...@flags_to_copy}; my @results = readfsgs($testfilename, \%readfsgs_flags); } but this has a bug: if $flags doesn't contain limit, %readfsgs_flags will contain (limit => undef); ie $readfsgs_flags will exist but be undefined. It shouldn't exist. What way of doing this would be most maintainable and readable? What is the Perlish way of doing things here? Thanks in advance, Philip -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/