检查字符串是否有点

时间:2014-01-31 13:16:43

标签: perl

我很难检查csv文件中的特定列是否包含点。

背后的想法是我必须结合两个列,这些列是人名和姓氏的名字。但在某些情况下,列中没有名字或姓氏。

为什么我需要知道它们是否是点?因为名字都是全名的缩短版本。

3 个答案:

答案 0 :(得分:3)

使用index检查字符串中的子字符串。它将返回第一个匹配的位置(从0开始),如果没有找到匹配则返回-1:

print index '.abc', '.';    # 0
print index 'abc.def', '.'; # 3
print index 'abc', '.';     # -1

if (index ($string, '.') >= 0) {
    # Do something
}

答案 1 :(得分:2)

Perl的优势之一是它的正则表达式引擎。使用正则表达式检查是否存在点是很容易的,虽然有点矫枉过正。例如:

#! /usr/bin/perl
use strict;
use 5.0100;

my $dotstring = "foo.bar";
my $nondotstring = "foodotbar";

foreach ( $dotstring, $nondotstring ) {
  if ( $_ =~ /\./ ) {
    say "There's a dot in $_";
  }
  else {
    say "There's no dot in $_";
  }
}

这只是一个通用示例,您需要自己将其纳入CSV解析。

答案 2 :(得分:1)

使用Text :: CSV :: Slurp读取您的文件,然后遍历结果行以查看名称列是否包含点。

my $data = Text::CSV::Slurp->load( file => ... )
for my $record (@$data) {
    if ($record->{Naam} =~ /\./) {
        ### Handle case here...
        ...
    }
}