9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perl : チルダ演算子を使った条件式サンプル

Last updated at Posted at 2015-05-21

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
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?