leykan leykan - 5 months ago 8
Perl Question

get param function array in perl

I want to get the array that I send in my function but it seem's to be empty.
I call

send_file();
with an array in the param

send_file($addr, @curfile);


And this is the way I get back the param

sub send_file($$)
{
my $addr = $_[0];
my @elem = @_;
...
}


Why
my @elem
is empty ? How could I get back the array without losing everything ?

Answer

You should pass your array by reference instead:

#!/usr/bin/perl

use strict;
use warnings;

my $test_scalar = 10;
my @test_array  = qw(this is a test);

sub test($\@)
{
    my ($scalar, $array) = @_;

    print "SCALAR = $scalar\n";
    print "ARRAY  = @$array\n";
}

test($test_scalar, @test_array);

system 'pause';

Output:

SCALAR = 10
ARRAY  = this is a test
Press any key to continue . . .

EDIT:

If you would like to do the same thing without passing by reference change your $$ to $@ and use shift so the first argument doesn't end up included in your array. Passing arrays by reference is better coding practice though . . . This is just to show you how it can be done without passing by reference:

#!/usr/bin/perl

use strict;
use warnings;

my $test_scalar = 10;
my @test_array  = qw(this is a test);

sub test($@)
{
    my ($scalar, @array) = @_;

    print "SCALAR = $scalar\n";
    print "ARRAY  = @array\n";
}

test($test_scalar, @test_array);

system 'pause';

This will get you the same output.

You can also get rid of the $@ altogether if you would like it really isn't necessary.

Comments