if文で比較演算子にチルダを使ったサンプル
- ~~(チルダチルダ)
- =~(イコールチルダ)
- !~(エクスクラメーションチルダ)
サンプル1:文字列比較
hoge1.pl
use strict;
use warnings;
use utf8;
my $hoge = "en";
if ($hoge ~~ ["ja","en"]) {
print "OK", "\n";
} else {
print "NG", "\n";
}
1;
実行結果
$ perl hoge1.pl
OK
if ($hoge == "ja" || $hoge == "en")
と同じように使えるので便利!
サンプル2:数値比較
hoge2.pl
use strict;
use warnings;
use utf8;
my $hoge = 1;
if ($hoge ~~ [2,3,4]) {
print "OK", "\n";
} else {
print "NG", "\n";
}
1;
実行結果
$ perl hoge2.pl
NG
サンプル3:パターンマッチ
hoge3.pl
use strict;
use warnings;
use utf8;
my $hoge = "en";
if ($hoge =~ /^ja|en/) {
print "OK", "\n";
} else {
print "NG", "\n";
}
1;
実行結果
$ perl hoge3.pl
OK
サンプル4:パターンマッチ(否定)
hoge4.pl
use strict;
use warnings;
use utf8;
my $hoge = "en";
if ($hoge !~ /^ja|en/) {
print "OK", "\n";
} else {
print "NG", "\n";
}
1;
実行結果
$ perl hoge4.pl
NG