0

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?

4

2 Answers 2

1

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
1
  • 1
    Thanks stevieb, this could be the most usefull thing I could do, as it seems, there's not any way to do what I was asking, or at least not in a easy way.
    – shayk_87
    Nov 18, 2016 at 9:36
0

Data::Dumper::Names does this using peek_my (from PadWalker) and refaddr (from Scalar::Util). But I suspect it's fragile and I wouldn't recommend it.

What are you actually trying to do?

2
  • Thanks, I'm going to try this module and see what happends. What I'm trying is to call this subroutine in multiple lines of a program and know wich array is testing at certain point and how the arrays are 'evolving'
    – shayk_87
    Nov 15, 2016 at 12:48
  • @shayk_87: I'm not saying that Data::Dumper::Names will solve your problem. I'm saying that you can look at the source code and use a similar approach.
    – Dave Cross
    Nov 15, 2016 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.