フリーCGIスクリプト配布サイト。
配列では各値は順に0番目、1番目、2番目…となっていましたが、連想配列ではキーをもとにして値を設定することができます。はじめのうちは何に使うと便利なのか解りにくいですが、プログラムの可読性を上げたり、処理の効率を上げたりすることができます。
連想配列を作成するには、以下のように記述します。
%fruit = (apple => "リンゴ", orange => "ミカン", grape => "ブドウ");
配列を作成するときは配列名の前に @
を付けましたが、連想配列の場合は %
を付けます。
上の例では apple
と リンゴ
、orange
と ミカン
、grape
と ブドウ
がそれぞれ対になっています。配列のように『0番目の値』『1番目の値』となるのではなく、『appleの値』『orangeの値』というように設定します。
以下に連想配列を作成してその内容を表示するプログラムを記載します。
#!/usr/local/bin/perl
%fruit = (apple => "リンゴ", orange => "ミカン", grape => "ブドウ");
print "Content-Type: text/html; charset=Shift_JIS\n\n";
print "<html>\n";
print "<head><title>サンプル</title></head>\n";
print "<body>\n";
print "<p>連想配列の内容は、$fruit{'apple'}と$fruit{'orange'}と$fruit{'grape'}です。</p>\n";
print "</body>\n";
print "</html>\n";
exit;
これを実行すると、ブラウザに 連想配列の内容は、リンゴとミカンとブドウです。
と表示されます。
$fruit{'apple'}
は、連想配列 fruit
の apple
の値、$fruit{'orange'}
は、orange
の値…となります。また、連想配列の内容を個別に参照するには、連想配列名の先頭には %
でなく $
を付けます。
上の例での連想配列 fruit
の内容を表にすると、以下のようになります。
表記 | 意味 | 値 |
---|---|---|
$fruit{'apple'} |
%fruit の apple の値 |
リンゴ |
$fruit{'orange'} |
%fruit の orange の値 |
ミカン |
$fruit{'grape'} |
%fruit の grape の値 |
ブドウ |
$fruit{'apple'}
や $fruit{'orange'}
とすれば、格納されている値を表示することができます。同様に、それぞれに別の内容を格納することが可能です。以下にサンプルプログラムを記載します。
#!/usr/local/bin/perl
%fruit = (apple => "リンゴ", orange => "ミカン", grape => "ブドウ");
$fruit{'orange'} = "メロン";
$fruit{'strawberry'} = "イチゴ";
print "Content-Type: text/html; charset=Shift_JIS\n\n";
print "<html>\n";
print "<head><title>サンプル</title></head>\n";
print "<body>\n";
print "<p>連想配列の内容は、$fruit{'apple'}と$fruit{'orange'}と$fruit{'grape'}と$fruit{'strawberry'}です。</p>\n";
print "</body>\n";
print "</html>\n";
exit;
これを実行すると、ブラウザに 連想配列の内容は、リンゴとメロンとブドウとイチゴです。
と表示されます。
$fruit{'orange'}
にはもともと ミカン
が格納されていますが、$fruit{'orange'} = "メロン";
の部分で新たに メロン
という文字を格納しています。また、$fruit{'strawberry'}
の内容はもともとカラですが、$fruit{'strawberry'} = "イチゴ";
で イチゴ
という文字を格納しています。