最新の「新着記事」はここから New!
2008-03-24
後置のif 後置のunless
ifやunlessは後置することもできます。
文 if 条件; 文 unless 条件;
後置のunless
$num1 = 1 unless defined $num1;
{}を使うことはできない。unlessの前も後ろも、裸の文。条件文、unlseeの前の処理が複雑になるときは使わない。デフォルト値を設定するときによく使われる。
後置のif
next if $line =~ /^#/;
die "Need array reference\n" if ref $obj ne "ARRAY";
{}を使うことはできない。ifの前も後ろも、裸の文。条件文、ifの前の処理が複雑になるときは使わない。 「next if 条件」や 「die "エラーメッセージ" if 条件」がよく使われる。
サンプルコード
後置のif、後置のunlessのサンプルです。
use strict; use warnings; # 後置のunless print "1: 後置のunlessの例\n"; my $num1; $num1 = 1 unless defined $num1; print "\$num1 = $num1\n"; my $num2 = 10; $num2 = 2 unless defined $num2; print "\$num2 = $num2\n"; # 後置のif print "1-2 : 後置のifの例(next if)\n"; my @lines = ( '#コメント', '1行目', '2行目' ); for my $line (@lines) { # 先頭が、#ならば、次の行へ next if $line =~ /^#/; print $line, "\n"; } print "\n"; print "1-2 後置のifの例(die if)\n"; my $obj = {}; # $objが、配列のリファレンスでないなら、 # エラーメッセージを出して、スクリプトを終了。 die "Need array reference\n" if ref $obj ne "ARRAY";
実行結果
1: 後置のunlessの例 $num1 = 1 $num2 = 10 1-2 : 後置のifの例(next if) 1行目 2行目 1-2 後置のifの例(die if) Need array reference


