简体   繁体   中英

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 ?

Don't use prototypes. Their purpose is to change parsing of the source which you don't need.

sub send_file
{
    my $addr = shift;
    my @elem = @_;
    ...
}

send_file($addr, @curfile);

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.

Why my @elem is empty ?

Your @elem is not empty, it has exactly two elements. First is value of $addr and second is size/number of elements in @curfile array. This is due $$ prototype definition which requires two scalars, so scalar @curfile is passed as second parameter.

How could I get back the array without loosing everything ?

Since you're not using prototype advantages, just omit prototype part,

sub send_file {
    my ($addr, @elem) = @_;
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM