[英]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. 因此,目标是要有一个名为“ test_array”的子例程,该子例程打印出名称,并将数组的内容作为参数传递给子例程。
What I would like is to print the array name where "%%ARRAY_NAME%%" is. 我想要的是在“ %% ARRAY_NAME %%”所在的位置打印数组名称。
Is there any way to recover this using special variables or to save this as a string inside a scalar? 有什么方法可以使用特殊变量来恢复它,或者将其另存为标量中的字符串?
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
Data::Dumper::Names does this using peek_my
(from PadWalker ) and refaddr
(from Scalar::Util ). Data :: Dumper :: Names使用
peek_my
(来自PadWalker )和refaddr
(来自Scalar :: Util )完成此操作。 But I suspect it's fragile and I wouldn't recommend it. 但是我怀疑它很脆弱,我不推荐它。
What are you actually trying to do? 您实际上想做什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.