神秘化Perl glob(*)

前端之家收集整理的这篇文章主要介绍了神秘化Perl glob(*)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
this question年,海报问如何做到以下一行:
sub my_sub {
    my $ref_array = shift;
    my @array = @$ref_array;
}

通过我对基本Perl魔法的了解,我将通过简单的使用以下方式避免:

sub my_sub {
    my $ref_array = shift;
    for (@$ref_array) {
      #do somthing with $_ here
    };

    #use $ref_array->[$element] here
}

然而在this answer年,SO的当地僧侣tchrist建议:

sub my_sub {
  local *array = shift();
  #use @array here
}

当我问

In trying to learn the mid-level Perl
magic,can I ask,what is it that you
are setting to what here? Are you
setting a reference to @array to the
arrayref that has been passed in? How
do you know that you create @array and
not %array or $array? Where can I
learn more about this * operator
(perlop?). Thanks!

我被建议要求它作为一个新的职位,虽然他给了很好的参考。无论如何,这里呢?有人可以解释什么被分配到什么以及如何来得到@array创建,而不是%array或$ array?谢谢。

解决方法

分配给球
*glob = VALUE

包含一些取决于VALUE类型的魔术(即,返回值,例如Scalar :: Util :: reftype(VALUE))。如果VALUE是对标量,数组,散列或子例程的引用,则只会覆盖符号表中的该条目。

这个成语

local *array = shift();
#use @array here

当子例程的第一个参数是数组引用时,可以作为文档。如果第一个参数是相反的,比如说一个标量引用,那么只有$ array而不是@array会受到赋值的影响。

一个小的演示脚本来看看发生了什么:

no strict;

sub F {
  local *array = shift;

  print "\@array = @array\n";
  print "\$array = $array\n";
  print "\%array = ",%array,"\n";
  print "------------------\n";
}

$array = "original scalar";
%array = ("original" => "hash");
@array = ("orignal","array");

$foo = "foo";
@foo = ("foo","bar");
%foo = ("FOO" => "foo");

F ["new","array"];        # array reference
F \"new scalar";          # scalar reference
F {"new" => "hash"};      # hash reference
F *foo;                   # typeglob
F 'foo';                  # not a reference,but name of assigned variable
F 'something else';       # not a reference
F ();                     # undef

输出

@array = new array
$array = original scalar
%array = originalhash
------------------
@array = orignal array
$array = new scalar
%array = originalhash
------------------
@array = orignal array
$array = original scalar
%array = newhash
------------------
@array = foo bar
$array = foo
%array = FOOfoo
------------------
@array = foo bar
$array = foo
%array = FOOfoo
------------------
@array =
$array =
%array =
------------------
@array = orignal array
$array = original scalar
%array = originalhash
------------------

perlmodperldata的附加文档。在引用之前的日子里,Perl的一部分,这个成语有助于传递数组和散列成子程序。

原文链接:https://www.f2er.com/Perl/172998.html

猜你在找的Perl相关文章