Should I use $_[0] or copy the argument list in Perl?
hash, perl
Solution
In this case there is no difference because you are passing reference to hash. But in case of passing scalar there will be difference:
sub rtrim {
## remove tailing spaces from first argument
$_[0] =~ s/\s+$//;
}
rtrim($str); ## value of the variable will be changed
sub rtrim_bugged {
my $str = $_[0]; ## this makes a copy of variable
$str =~ s/\s+$//;
}
rtrim($str); ## value of the variable will stay the same
If you're passing hash reference, then only copy of reference is created. But the hash itself will be the same. So if you care about code readability then I suggest you to create a variable for all your parameters. For example:
sub parse {
## you can easily add new parameters to this function
my ($hr) = @_;
my $var1 = $hr->{'elem1'};
my $var2 = $hr->{'elem2'};
my $var3 = $hr->{'elem3'};
my $var4 = $hr->{'elem4'};
my $var5 = $hr->{'elem5'};
}
Also more descriptive variable names will improve your code too.
Problem
If I pass a hash to a sub: ``` parse(\%data); ``` Should I use a variable to `$_[0]` first or is it okay to keep accessing `$_[0]` whenever I want to get an element from the hash? clarification: ``` sub parse { $var1 = $_[0]->{'elem1'}; $var2 = $_[0]->{'elem2'}; $var3 = $_[0]->{'elem3'}; $var4 = $_[0]->{'elem4'}; $var5 = $_[0]->{'elem5'}; } # Versus sub parse { my $hr = $_[0]; $var1 = $hr->{'elem1'}; $var2 = $hr->{'elem2'}; $var3 = $hr->{'elem3'}; $var4 = $hr->{'elem4'}; $var5 = $hr->{'elem5'}; } ``` Is the second version more correct since it doesn't have to keep accessing the argument array, or does Perl end up interpereting them the same way anyhow?