構文 |
|
index 文字列, 検索文字列, 検索開始位置 index 文字列, 検索文字列 |
返り値 |
|
検索文字列の出現位置 |
説明
- 文字列の中で検索文字列が最初に出現する位置を返します。検索開始位置が指定してある場合には指定されている位置から探し始めます。検索開始位置を省略した場合は先頭から探し始めます。
- 検索文字列が見つからない場合には-1を返します。
使用例
#!/usr/bin/perl
use strict;
use warnings;
my $str = 'A fool and his money are soon parted.';
my $search = 'money';
my $pos = index $str, $search;
if ($pos > -1) {
print "Found.\n";
} else {
print "Not found.\n";
}
#!/usr/bin/perl
use strict;
use warnings;
my $str = 'It takes money to make money.';
my $search = 'money';
my $pos = index $str, $search;
if ($pos > -1) {
my $rpos = rindex $str, $search;
printf "前方から探した場合の発見位置[%d]\n", $pos;
printf "後方から探した場合の発見位置[%d]\n", $rpos;
} else {
print "Not found.\n";
}
#!/usr/bin/perl
use strict;
use warnings;
my $str = 'A fool and his money are soon parted.';
my $search = qr/money/;
if ($str =~ m/$search/) {
print "Found.\n";
} else {
print "Not found.\n";
}