简述perl的引用(包括标量、数组、hash等数据类型的引用)

  • perl的引用
  • 数组的解引用
  • 二维数组的引用
  • hash哈希又叫散列的引用

perl的引用,类似C语言的指针;意义都是指向一个内存空间的地址。比如下述例子中,脚本输出的信息SCALAR(0x7836d0)代表标量数据的存储地址;ARRAY(0x93d6d0)代表数组数据的存储地址。

引用一般会包含“定义引用”,“解引用”两个步骤。“定义引用”是为数据定义内存地址;“解引用”是取内存地址里的数据。

引用的变量是标量类型,那么解引用就必须用标量符号$;
引用的变量是数组类型,那么解引用就必须用数组符号@;
引用的变量是散列类型,那么解引用就必须用散列符号%;
….
总之,解引用和定义引用的数据类型,要保持一致。

另外,解引用的过程中,要关心地址的个数,从而决定是用标量还是数组收集。

perl的引用

qilei@AFAAW-704030720:~/array_2d$ cat 1.pl
#!/usr/bin/perl
use strict;
use warnings;

my $value = 10;
my $pointer = \$value;
print "Pointer Address $pointer of $value \n";
print "What Pointer *($pointer) points to $$pointer\n";

qilei@AFAAW-704030720:~/array_2d$ ./1.pl
Pointer Address SCALAR(0x7836d0) of 10
What Pointer *(SCALAR(0x7836d0)) points to 10
qilei@AFAAW-704030720:~/array_2d$

数组的解引用

引用的变量是数组类型,那么解引用就必须用数组符号@。
非数组类型的引用变量同理,即解引用和定义引用的数据类型都要注意保持一致。

qilei@AFAAW-704030720:~/array_2d$ cat 2.pl
#!/usr/bin/perl
use strict;
use warnings;

my @names =(1,2,3);
print "$#names\n@names\n";
my $address = \@names;
sub listem{
   my ($list) = @_;
   print $list."\n";
   print (@$list[1],"\n");
}
&listem(\@names);
qilei@AFAAW-704030720:~/array_2d$ ./2.pl
2
1 2 3
ARRAY(0x93d6d0)
2
qilei@AFAAW-704030720:~/array_2d$

二维数组的引用

qilei@AFAAW-704030720:~/array_2d$ cat run.pl
#!/usr/bin/perl
use strict;
use warnings;

my @array1=("a1","b1","c1","d1");
my @array2=("a2","b2","c2","d2");
my @array3=("a3","b3","c3","d3");
my @array_2d=(@array1,@array2,@array3);
print "@array_2d";
print "\n";
print "$array_2d[1]";
print "\n";
################
@array_2d=(\@array1,\@array2,\@array3);
print "@array_2d";
print "\n";
print "$array_2d[1]";
print "\n";
print "$array_2d[1][1]";
print "\n";
qilei@AFAAW-704030720:~/array_2d$ ./run.pl
a1 b1 c1 d1 a2 b2 c2 d2 a3 b3 c3 d3
b1
ARRAY(0x175a6e0) ARRAY(0x175a788) ARRAY(0x175a878)
ARRAY(0x175a788)
b2
qilei@AFAAW-704030720:~/array_2d$

hash(哈希,又叫散列)的引用

hash数据类型,不能直接用print "%var"去打印。究其原因,个人暂时理解为,hash数据存储方式与标量数组不一样,是key和value组合在一起的;所以不能直接打印。此时用Data::Dumper package打印hash数据,方便阅读。

但是,通过实践发现,print %var;也可以打印hash数据,但是格式不好看,不容易阅读。

qilei@AFAAW-704030720:~/array_2d$ cat 3.pl
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %parameters=("p1"=>"xx1",
                "p2"=>"xx2",
                "p3"=>"xx3");
print %parameters;
print "\n";
print Dumper(\%parameters);
print "\n";
print "$parameters{p2}";
print "\n";

my $address = \%parameters;
print Dumper($address);
print "\n";
print %$address;
print "\n";
print $$address{p3};
print "\n";
qilei@AFAAW-704030720:~/array_2d$ ./3.pl
p3xx3p1xx1p2xx2
$VAR1 = {
          'p3' => 'xx3',
          'p1' => 'xx1',
          'p2' => 'xx2'
        };

xx2
$VAR1 = {
          'p3' => 'xx3',
          'p1' => 'xx1',
          'p2' => 'xx2'
        };

p3xx3p1xx1p2xx2
xx3
qilei@AFAAW-704030720:~/array_2d$

你可能感兴趣的:(perl)