Perl_引用


#about ref num

my $num=10;

my $rnum=\$num;

$$rnum += 2;

print $$rnum."\n";#print 12

${$rnum} += 2;

print ${$rnum}."\n";#print 14

my $rdnum=\10;


#ref string
my $a="string1";
my $ra=\$a;
my $rs=\"string2";

my @array = (10,20);
my $rarray=\@array;
print $$rarray[1]."\n";# print 20
print ${$rarray}[1]."\n";# print 20
push @$rarray, 30;

print $$rarray[2]."\n";# print 30
print ${$rarray}[2]."\n";# print 30
print $#$rarray."\n";# print 2
print $#{$rarray}."\n";# print 2


#引用匿名数组

$ra = [ ];
$ra = [1,"hello"];

print ${$ra}[1]."\n";#print hello


#ref hash

my %hash =("key1"=>"value1","key2"=>"value2","key3"=>"value3");
my $rhash=\%hash;
print $$rhash{"key1"}."\n";# print value1
print ${$rhash}{"key1"}."\n";# print value1
my @slice=@$rhash{'key1','key2'};# content:i value1, value2

#分割哈希
my @slice1=@{$rhash}{'key1','key2'};# content:i value1, value2

print $slice[0]."\n";#print value1
print $slice1[0]."\n";#print value1


#引用匿名哈希
$rhash = {};
$rhash = {"k1","v1","k2","v2"};

print ${$rhash}{"k1"}."\n";#print v1
$rhash ={"k3"=>"v3","k4"=>"v4"};
print ${$rhash}{"k3"}."\n";#print v1


#引用数组、哈希元素

my $r_array_element=\$array[1];
my $r_hash_element=\$hash{"key1"};


#嵌套数据结构

my %parent=('name'=>'par','age'=>'50');
my %ch1=('name'=>'tom','age'=>'10');
my %ch2=('name'=>'tim','age'=>'12');
my @children=(\%ch1,\%ch2);
$parent{'children'}=[\%ch1,\%ch2];#$parent{'children'}=\@children;
print $parent{'children'}->[1]->{'age'}."\n";#print child 2, tim's age: 12
print $parent{'children'}[0]{'name'}."\n";#print child 1, tom's name: tom
%parent=();
%parent = (
'name'=>'par','age'=>'50',
'children'=>[{'name'=>'tom','age'=>10},{'name'=>'tim','age'=>12}]
);

print $parent{'children'}->[1]->{'age'}."\n";#print child 2, tim's age: 12
print $parent{'children'}[0]{'name'}."\n";#print child 1, tom's name: tom
print values(%parent);#it's not value

你可能感兴趣的:(Perl技巧)