Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing array reference to sub-routine 1

Status
Not open for further replies.

varakal

IS-IT--Management
Mar 18, 2004
114
US
I am having problem with passing array reference to sub-routine. I think I should be doing a small mistake somewhere.

Code:
print "Above function: $data[0]\n";
my $line = array_refer("\@data");

sub array_refer {
        my @data = @$_[0];
        print "In function: $data[0]\n";
}

The output I get is:

Above function: 1234567
In function:

Where am I doing wrong? THanks in advance.
 
what is @data before you get to this part of your script?

You don't want to use the double-quotes in: array_refer("\@data")

just use: array_refer(\@data)

Is this what you are trying to do?:

Code:
my @data = (12345, 67890);

print "Above function: $data[0]\n";
my $line = array_refer(\@data);

sub array_refer {
        my ($array_ref) = @_;
        print "$array_ref->[0]\n";
}
 
In the function, I should have used like this:

Code:
my @data = @{@_[0]};
print "In function: $data1[0]\n";

But the main problem is quotes. Thanks Kevin for this.

Varakal
 
you can do it like that but it's unusual and completely unecessary. Don't use references when you don't need to. In that example you don't need to use a reference at all, but maybe you are just practicing and experimenting to see how perl references work. :)
 
I wanted to use that notation because, I will be using that array everywhere, and I would want to minimize the number of '->' or '$$' signs.
And also, am I using extra references there? I didnt get it. I felt that what all I am trying to do is copy the whole array the reference is pointing to, into a @data array?
 
to copy the whole array to the sub routine just do this:

Code:
my @data = (0 .. 100);

print "Above function: $data[0]\n";
my $line = array_refer(@data);

sub array_refer {
        my @data = @_;
        print "$data[0] $data[99]\n";
}

its very easy to pass a single array or a scalar or even a hash this way. The problem comes in when you want to pass more than one list to a sub routine because multiple lists are flattened in the system array @_ and become one long list. To avoid this flattening of lists you pass references to a sub routine:

Code:
my @digits = (0 .. 100);
my @alphas = ('a' .. 'z');

&array_refer(\@digits,\@alphas);

sub array_refer {
        my @digits = @{$_[0]};
        my @alphas = @{$_[1]};
        print "$digits[10] $alphas[10]\n";
}





 
That is true. As a programmer in other languages, I was never into the idea of sending the array as flattened list.
Thanks
Varakal
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top