问个Perl的问题

来源:百度知道 编辑:UC知道 时间:2024/09/20 07:10:42
my @names = (’fred’, ’barney’, ’wilma’, ’freldy’, ’wilma-jean’, ’wilma’);
my %h;

foreach my $n ( @names ) {
if ( $h{$n} ) {
print "$n is duplicated\n";
}
$h{$n} = 1;
}

请问怎样 修改才能使它匹配名字的前3个字母,比如wilma-jean也是dulicated的?

#!/usr/bin/perl

my @names = ('fred','barney','wilma','freldy', 'wilma-jean', 'wilma');
my %h;

foreach my $n ( @names ) {
my $str = substr ($n , 0 , 3 ) ; #取$n的前3个字母作匹配
foreach my $key ( sort %h ) { #这里增加一个循环
if ( $key =~ /^$str/ ) { #拿%h的key和$n匹配
print "$n is duplicated\n";
}
}
$h{$n} = 1;
}

运行结果是:
freldy is duplicated
wilma-jean is duplicated
wilma is duplicated
wilma is duplicated

my @names = (’fred’, ’barney’, ’wilma’, ’freldy’, ’wilma-jean’, ’wilma’);
my %h;

foreach my $n ( @names ) {
$n2=substr($n,0,3); # 这一行是增加的,去前三个字符
if ( $h{$n2} ) {
print "$n is duplicated\n";
}
$h{$n2} = 1;
}

my @names=('fred','barney','wilma','freldy','wilma-jean','wilma');
for ($i=0;$i<@names;$i++)