Perl字符在带有模式的字符串中搜索

时间:2014-03-12 10:21:17

标签: perl

是否有内置函数可确定字符串中是否存在字符。另外,如何确定值是字符串还是数字。

2 个答案:

答案 0 :(得分:0)

perl中有一个内置函数,称为索引函数,也使用模式匹配,如

使用index:index($ stringvariable," char to search"); 确定一个数字是否使用代码m / \ d / 如果你想确定一个值是否是一个字符串使用m / \ D / 使用模式匹配技术。

答案 1 :(得分:0)

Perl的标量是一个字符串和一个数字同时。要测试标量是否可以在没有任何警告的情况下用作数字:

use Scalar::Util qw/looks_like_number/;

my $variable = ...;
if (not defined $variable) {
    # it is not usable as either a number or a string, as it is "undef"
}
elsif (looks_like_number $variable) {
    # it is a number, but can also be used as a string
}
else {
    # you can use it as a string
}

实际上,对于可能会或可能不会用作数字或字符串的对象,故事会更复杂一些。此外,looks_like_number可以返回InfinityNaN(不是数字)的真值,这可能不是您认为的数字。


要测试字符串是否包含某个子字符串,可以使用正则表达式或index函数:

my $haystack = "foo";
my $needle   = "o";
if (0 <= index $haystack, $needle) {
    # the $haystack contains the $needle
}

有些人更喜欢等效的测试-1 != index ...