shayk_87 shayk_87 - 19 days ago 5
Perl Question

How to recover a element name used as parameter in a subroutine?

I'm guessing if it's possible to recover or save inside a scalar the "items" names used as parameters for a subroutine.

The following code explains better what I'm referring

sub test_array{

print "\n";
print "TESTING ARRAY ".%%ARRAY_NAME%%."\n";
print "\n";
print " \'".join ("\' , \'" , @_)."\'"."\n";
print "\n";

}

@list= qw/uno dos tres/;

test_array(@list);


So the goal is to have a subroutine called "test_array" that prints the name and content of the array is being passed to subroutine as parameter.

What I would like is to print the array name where "%%ARRAY_NAME%%" is.

Is there any way to recover this using special variables or to save this as a string inside a scalar?

Answer

I think you'd be much better off just sending in two parameters... the array's 'name', and the array itself:

sub test_array {
    my ($name, @array) = @_;
    print "array: $name\n";
    print join ', ', @array;
}

Then:

my @colours = qw(orange green);
test_array('colours', @colours);

...

my @cities = qw(toronto edmonton);
test_array('cities', @cities);

Or even:

test_array('animals', qw(cat dog horse));

Another way that may help automate things a bit, is use a global hash to store the array's location as the key, with it's name as the value, then pass the array reference to the sub:

use warnings;
use strict;

my %arrs;

my @animals = qw(cat dog);

$arrs{\@animals} = 'animals';

my @colours = qw(orange green);

$arrs{\@colours} = 'colours';

test_array(\@animals);
test_array(\@colours);

sub test_array {
    my $array = shift;

    print "$arrs{$array}\n";

    print join ', ', @$array;
    print "\n";
}

Output:

animals
cat, dog
colours
orange, green