我有一个字符串说
my $str = "Hello Hi Bye"
,我希望提供此字符串来剪切命令获取字段。
有人可以帮我怎么做?
那怎么样?我实际上是想这样做...我有一个数组:
my @str = ("hello hi bye","hello hi you","abc def ghi","abc def jkl");
我想提供这个数组来剪切前两个字段并获得其中唯一的字段。
类似输出应该是"hello hi"
和"abc def"
并获得这两个字段的唯一组合的计数,这里是2 ..
答案 0 :(得分:4)
use warnings;
use strict;
my $str = "Hello Hi Bye";
my @fields = split /\s+/, $str;
更新:要回答您的新问题......无论何时您想要“独特”,请考虑“哈希”:
use warnings;
use strict;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
my %count;
my @str = ("hello hi bye","hello hi you","abc def ghi","abc def jkl");
for (@str) {
my @flds = (split)[0..1];
$count{"@flds"}++;
}
print Dumper(\%count);
__END__
$VAR1 = {
'abc def' => 2,
'hello hi' => 2
};
答案 1 :(得分:1)
尝试使用split
function:
my $str = "Hello Hi Bye";
my @fields = split(/\s+/, $str); # => ('Hello', 'Hi', 'Bye')