在perl中连接字符串时出现意外结果

时间:2013-04-23 17:04:18

标签: perl

我正在尝试执行以下脚本但没有获得所需的输出。它似乎仍然保留了旧的价值,并保持连接。

./ test.pl -v v10,v11,v12

实际结果=> 'V10', 'V11', 'V10', 'V12', 'V10', 'V11', 'V10'

预期结果=> 'V10', 'V11', 'V12'

你可以帮忙解决这个问题吗?

#!/usr/bin/perl

use strict;
use warnings;
use Getopt::Long;

my ($versionFlag,$finalVersionList);

sub validateInputAndFilter
{
        my ($passedVersionList) = @_;
        $finalVersionList ="";

        my @versionList = split(",",$passedVersionList);
        foreach my $ver (@versionList)
        {
                if($ver =~ m/^v[0-9][0-9]$/)
                {
                        $finalVersionList .= "'$ver',$finalVersionList";
                }
                else
                {
                        print "\nWARNING: Passed version *** $ver *** is NOT in expected format...skipping...\n";
                }
        }
        $finalVersionList =~ s/\,$//;
        print "\n\nfinalVersionList => $finalVersionList\n\n";
}

GetOptions('v|version=s' => \$versionFlag) || die "Please pass version list separated by comma";

if(defined $versionFlag)
{
        &validateInputAndFilter("$versionFlag");
}
else
{
        die "Please pass version list separated by comma";
}
exit 0;

2 个答案:

答案 0 :(得分:4)

此:

$finalVersionList .= "'$ver',$finalVersionList";

应该是:

$finalVersionList .= "'$ver,'";

$foo .= $bar;相当于:

$foo = $foo . $bar;

因此,$finalVersionList .= "'$ver',$finalVerionList";相当于:

$finalVersionList = $finalVersionList . "'$ver',$finalVersionList";

答案 1 :(得分:2)

变化:

 $finalVersionList .= "'$ver',$finalVersionList";

要:

 $finalVersionList .= "'$ver',";

你在这里做了多个追加。你原来的相当于:

 $finalVersionList = $finalVersionList . "'$ver',$finalVersionList";

这不是你想要的。如果您希望'$ver$',位于列表的最后位置,您可以执行以下操作:

$finalVersionList = "'$ver'," . $finalVersionList;

或:

 $finalVersionList = "'$ver',$finalVersionList";