- Home ›
- Perlにおける正規表現 ›
- パターンへの変数展開 ›
- HERE
m//演算子の区切りに''を使った場合
広告
パターン内で記述された変数や配列は、ダブルクオーテーションで囲われた文字列の中に記述された場合と同じく変数展開が行われますが、パターンの記述を行う時、m//演算子の区切りに''を使った場合は変数展開は行われません。
m'パターン'
具体的な例で考えてみます。
my @pattern = ("color", "red");
my $str = "background color red";
if ($str =~ /@pattern/){
print "$str¥n";
}
上記のようにパターンの記述を「/@pattern/」のように行った場合は、パターン内に配列の変数展開が行われます。
my @pattern = ("color", "red");
my $str = "background color red";
if ($str =~ m'@pattern'){
print "$str¥n";
}
上記の場合は配列の変数展開が行われずに「@pattern」と言う文字列が記述されたパターンとして解釈されます。
サンプルプログラム
では簡単なプログラムで確認して見ます。
use strict;
use warnings;
use utf8;
binmode STDIN, ':encoding(cp932)';
binmode STDOUT, ':encoding(cp932)';
binmode STDERR, ':encoding(cp932)';
$" = "|";
&check1('hogehoge@color');
&check2('hogehoge@color');
&check1("border white");
&check2("border white");
sub check1{
my ($str) = @_;
if ($str =~ m'(@color)'){
print "パターン: m'(¥@color)'¥n";
print "対象文字列: $str¥nマッチ部分: $&¥n¥n";
}
}
sub check2{
my ($str) = @_;
my @color = ("black", "red", "white");
if ($str =~ m/(@color)/){
print "パターン: m/(¥@color)/¥n";
print "配列¥@color: @color¥n";
print "対象文字列: $str¥nマッチ部分: $&¥n¥n";
}
}
上記を「test3-1.pl」の名前で保存します(文字コードはUTF-8です)。そしてコマンドプロンプトを起動し、プログラムを保存したディレクトリに移動してから次のように実行して下さい。
今回はパターンの記述方法として「m''」と「m//」を使用しています。使用している区切り文字の違いによって同じパターンであってもマッチする文字列は異なります。
( Written by Tatsuo Ikura )
PerlPlus