Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl subroutine argument lists - "pass by alias"?

I just looked in disbelief at this sequence:

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

I had understood all along that Perl arguments were passed by value, so whenever I've needed to pass in a large structure, or pass in a variable to be updated, I've passed a ref.

Reading the fine print in perldoc, however, I've learned that @_ is composed of aliases to the variables mentioned in the argument list. After reading the next bit of data, getline() returns it with $_[0] = $data;, which stores $data directly into $line.

I do like this - it's like passing by reference in C++. However, I haven't found a way to assign a more meaningful name to $_[0]. Is there any?

like image 382
Chap Avatar asked May 28 '13 03:05

Chap


1 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
like image 190
Joel Berger Avatar answered Nov 25 '22 15:11

Joel Berger