今回は、連想配列です。Perlではハッシュと呼びます。
ハッシュ変数は%が頭につきます。
takk@deb9:~/pl$ cat test.pl
%a = ( 'dog' => '犬',
'cat' => '猫',
'fox' => '狐' );
print $a{'dog'} . "\n";
takk@deb9:~/pl$
対応する要素が取得できます。
takk@deb9:~/pl$ perl test.pl 犬 狐 猫 takk@deb9:~/pl$
=>は、,カンマと同じなので、カンマで書くこともできます。
takk@deb9:~/pl$ cat test.pl
%a = ( 'dog' , '犬',
'cat' , '猫',
'fox' , '狐' );
print $a{'dog'} . "\n";
print $a{'fox'} . "\n";
print $a{'cat'} . "\n";
print $a{'bird'} . "\n";
takk@deb9:~/pl$ perl test.pl
犬
狐
猫
takk@deb9:~/pl$
キーの文字列は、クォートを省略できます。
takk@deb9:~/pl$ cat test.pl
%a = ( dog , '犬',
cat , '猫',
fox , '狐' );
print $a{'dog'} . "\n";
print $a{'fox'} . "\n";
print $a{'cat'} . "\n";
print $a{'bird'} . "\n";
takk@deb9:~/pl$ perl test.pl
犬
狐
猫
takk@deb9:~/pl$
値の文字列はクォートを省略できません。
takk@deb9:~/pl$ cat test.pl
%a = ( dog , 犬,
cat , 猫,
fox , 狐 );
print $a{'dog'} . "\n";
print $a{'fox'} . "\n";
print $a{'cat'} . "\n";
print $a{'bird'} . "\n";
takk@deb9:~/pl$ perl test.pl
Unrecognized character \xE7; marked by <-- HERE after = ( dog , <-- HERE near column 14 at test4.pl line 1.
takk@deb9:~/pl$
keysとvaluesで全キー、全値を取得できます。
takk@deb9:~/pl$ cat test.pl
%a = ( dog , '犬',
cat , '猫',
fox , '狐' );
@all_keys = keys %a;
@all_values = values %a;
print "@all_keys\n";
print "@all_values\n";
takk@deb9:~/pl$ perl test.pl
cat dog fox
猫 犬 狐
takk@deb9:~/pl$


コメント