Should I use $ _ [0] or copy the argument list in Perl?

If you pass the hash to sub:

parse(\%data);

Should I use the variable in $_[0]the first place or is it okay to continue accessing $_[0]whenever I want to get an item from a 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 does not need to continue accessing the array of arguments, or does Perl end up interacting with them the same way?

+3
source share
6 answers

In this case, there is no difference because you are passing the hash reference. But in case of passing the scalar there will be a 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

-, . . , , . :

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'};
}

.

+11

shift @_ .

, shift, -:

sub parse
{
    my $hr = shift;
    my ($var1, $var2, $var3, $var4, $var5) = @{$hr}{qw(elem1 elem2 elem3 elem4 elem5)};
}

, - , (, , , ? ) - hashref, ?

+7

-; . , /. , , ... $data $x, , , .

, , ops perl. $_[0], : glob, glob, ( ), . $hr, , . @_, , ops $_[0] op ( 0 255 ), , - deref ( ), .

, ( ) .

+5

, $_[0] , . .

Why are you copying all hash values ​​into variables? Just leave them in the hash where they belong. This is a much better optimization than the one you are thinking about.

+4
source

The same, although the second is more clear.

0
source

Since they work, both of them are fine, the usual practice is to switch shiftoff.

sub parse { my $hr = shift; my $var1 = $hr->{'elem1'}; }
0
source

Source: https://habr.com/ru/post/1723260/


All Articles