条件分岐

if文(条件に一致する処理を記述。elsif文の追加により複数の条件を設定可能)

# 設定(引数の値を取得)
$var = $ARGV[0];
 
# 判定
if($var == 10){
	print "test1";
 
}elsif($var == 20){
	print "test2";
 
}else{
	print "test3";
 
}
 
>perl sample.pl 10
test1
>perl sample.pl 20
test2
>perl sample.pl
test3
>
 

if修飾子(処理の直後にif文を記述し、一致する場合のみ処理を実行する)

# 設定(引数の値を取得)
$var = $ARGV[0];
 
# 判定
print "test10" if($var == 10);
 
>perl sample.pl 10
test10
>perl sample.pl
 
>
 

unless文(条件に一致しない場合に処理を実行する)

# 設定(引数の値を取得)
$var = $ARGV[0];
 
# 判定
unless($var == 10){
	print "test1";
 
}else{
	print "test3";
 
}
 
>perl sample.pl 20
test1
>perl sample.pl 10
test3
>
 

unless修飾子(処理の直後にif文を記述し、一致しない場合のみ処理を実行する)

# 設定(引数の値を取得)
$var = $ARGV[0];
 
# 判定
print "test10" unless($var == 10);
 
 
>perl sample.pl 20
test10
>perl sample.pl 10
 
>
 

条件演算子(1行で処理の一致、不一致を記述する)

# 設定
$var = $ARGV[0];
 
# 判定
$var == 10 ? print "sample01" : print "sample02";
 
 
>perl sample.pl 10
sample01
>perl sample.pl 20
sample02
>
 





最終更新:2012年01月02日 21:19