pass array reference

B

bjlockie

I'm trying to pass a reference to an array so I can modify it in a function and see the changes outside the function.

I tried:

#!/bin/perl

use strict;
use warnings;

my @myarray = ();
&loadFile( '/etc/resolv.conf', \@myarray );

print "Loaded $#myarray\n";

sub loadFile
{
my $filename = $_[0];
# input as a reference
my (@inputArray) = @{$_[1]};

open( FILE, "<$filename" ) or die "Can't open file ($filename): $!\n";
@inputArray = <FILE>;
close( FILE );

print "Loaded $#inputArray from $filename\n";
}
 
R

Rainer Weikusat

bjlockie said:
#!/bin/perl

use strict;
use warnings;

my @myarray = ();
&loadFile( '/etc/resolv.conf', \@myarray );

Don't use & to invoke a subroutine except if you actually
intend to use its 'special powers': 1. Bypass prototype checking.
2. 'Call forwarding': invoke the subroutine with the current @_ as
'argument vector'.
print "Loaded $#myarray\n";

sub loadFile
{
my $filename = $_[0];
# input as a reference
my (@inputArray) = @{$_[1]};

Here, you copy the contents of @myarray into @input array. What you
actually need to do is to work with the passed reference, eg
(untested)

my $inputArray = $_[1];

open( FILE, "<$filename" ) or die "Can't open file ($filename): $!\n";
@$inputArray = <FILE>;
close( FILE );

print "Loaded $#$inputArray from $filename\n";
}
 
J

Jim Gibson

bjlockie said:
I'm trying to pass a reference to an array so I can modify it in a function
and see the changes outside the function.

I tried:

#!/bin/perl

use strict;
use warnings;

my @myarray = ();
&loadFile( '/etc/resolv.conf', \@myarray );

print "Loaded $#myarray\n";

sub loadFile
{
my $filename = $_[0];
# input as a reference
my (@inputArray) = @{$_[1]};

open( FILE, "<$filename" ) or die "Can't open file ($filename): $!\n";
@inputArray = <FILE>;
close( FILE );

print "Loaded $#inputArray from $filename\n";
}

You are making a local copy of the array and modifying that. This
should work (untested):

sub loadFile
{
my( $filename, $arrayref ) = @_;

open( my $file, '<', $filename ) or die ...;
@{$arrayref} = <$file>;
close($file);

print( scalar @{$arrayref}, " records read from $filename\n");
}
 
R

Rainer Weikusat

[...]
sub loadFile
{
my( $filename, $arrayref ) = @_;

open( my $file, '<', $filename ) or die ...;
@{$arrayref} = <$file>;

The curlies are not necessary in this case, cf

Anywhere you'd put an identifier (or chain of identifiers) as
part of a variable or subroutine name, you can replace the
identifier with a simple scalar variable containing a
reference of the correct type:
[perlref(1)]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,189
Members
46,735
Latest member
HikmatRamazanov

Latest Threads

Top