■Creating References
1. You can create areference to any named variable or subroutine with a backslash. $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&handler; $globref = \*STDOUT;
2. You can create areference to an anonymous array with square brackets. $arrayref = [1,2,['a','b','c','d']];
3. You can create areference to an anonymous hash with braces. $hashref = {'Adam' => 'Eve','Clyde' => $bonnie,'Antony' => 'Cleo' . 'patra',}; 4. You can create areference to an anonymous subroutine by using sub without a subroutine name. $coderef = sub{print "Boink!\n"}; #&$$coderef prints "Boink!" 5. References to filehandles or directory handles can be created by referring the typeglob of the same name. &splutter(\*STDOUT); Sub splutter { my $fh = shift; print $fh "..........\n"; }
6. References can be created by dereferencing them.
■Dereferencing References
1. Using a Variable as a Variable Name $bar = $$scalarref; push (@$arrayref, $filename); $$arrayref[0] = "January"; @$arrayref[4..6] = qw/May June July/; %$hashref = (KEY => "RING", BIRD => "SING"); $$hashref{KEY} = "VALUE"; @$hashref{"KEY1","KEY2"} = ("VAL1", "VAL2"); &$coderef(1,2,3); 2. Using a BLOCK as a Variable Name $bar = ${$scalarref}; push (@{$arrayref}, $filename); ${$arrayref}[0] = "January"; @{$arrayref}[4..6] = qw/May June July/; %{$hashref} = (KEY => "RING", BIRD => "SING"); ${$hashref}{KEY} = "VALUE"; @{$hashref}{"KEY1","KEY2"} = ("VAL1", "VAL2"); &{$coderef}(1,2,3); 3. Using the Arrow Operator $$arrayref[0] = "January"; ${$arrayref}[0] = "January"; $arrayref->[0] = "January"; (上記のどの書き方でもOK) &$coderef(1,2,3); &{$coderef}(1,2,3); $coderef->(1,2,3); (上記のどの書き方でもOK) $listref->[2][2] = "hello"; $$listref[2][2] = "hello"; (上記のどの書き方でもOK) ■Array of Arrays ※以下はすべて同じ
for $i (1..10) { @array = somefunc ($i); $AoA[$i] = [@array]; } for $i (1..10) { @array = somefunc ($i); @{$AoA[$i]} = @array; } for $i (1..10) { my @array = somefunc ($i); $AoA[$i] = \@array; }
for $i (1..10) { $AoA[$i] = [somefunc ($i)]; }
■Hash of Arrays
for $group ("simpsons", "jetsons","flintstones") { $HoA{$group} = [get_famly($group)]; } $HoA{$group}[1] =~ s/(\w)/\u$1/; #最初の文字を大文字に for $family (sort {@{$HaA{$b}} <=> @{$HaA{$a}}} keys %HoA) { print "$family: ", join(",", sort @{$HaA{$family}}), "\n"; } #各Arrayの要素数で、Hashのキーを多い方からソートして、キーと要素(アスキー順にソートしたもの)を順にプリント ■Hash of Hashes
for $family (sort {keys %{$HaH{$b}} <=> keys %{$HaH{$a}}} keys %HoH) { print "$family: "; for $role (sort keys %{$HaH{$family}}) { print "$role=$HaH{$family}{$role}"; } print "\n"; } #各Hashの要素数(キーの数)で、Hashのキーを多い方からソートして、キーと要素(アスキー順にソートしたもの)を順にプリント
|
2003年10月30日(木)
No.47
|
|