Perl subroutine argument lists - "pass by alias"?

I just looked perplexed in this sequence:

my $line; $rc = getline($line); # read next line and store in $line 

I always understood that Perl arguments were passed by value, so whenever I needed to go through a large structure or pass in a variable to be updated, I passed a link.

Reading the fine print in perldoc, however, I found out that @_ consists of aliases for the variables mentioned in the argument list. After reading the next bit of data, getline () returns it with $ _ [0] = $ data; which saves $ data strong> directly to $ line .

I like this - it's like passing by reference in C ++. However, I did not find a way to give the more meaningful name $ _ [0] . Whether there is a?

+6
source share
3 answers

You can, its not very pretty:

 use strict; use warnings; sub inc { # manipulate the local symbol table # to refer to the alias by $name our $name; local *name = \$_[0]; # $name is an alias to first argument $name++; } my $x = 1; inc($x); print $x; # 2 
+7
source

The easiest way is probably to just use a loop, since loops pseudonize their name arguments; i.e.

 sub my_sub { for my $arg ( $_[0] ) { code here sees $arg as an alias for $_[0] } } 
0
source

A version of @Steve code that allows for several different arguments:

 sub my_sub { SUB: for my $thisarg ( $_[0] ) { for my $thatarg ($_[1]) { code here sees $thisarg and $thatarg as aliases last SUB; } } } 

Of course, this introduces multi-level attachments and its problems with code readability, so use it only if absolutely necessary.

0
source

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


All Articles