perl中的替换错误

时间:2014-02-22 18:08:35

标签: perl

#!/usr/bin/perl                                                                                                                                                                  

use strict;
use warnings;

my $directory = shift @ARGV or die "Please specify a directory";

if(opendir(DIR , $directory))

{
    my @files = readdir(DIR);

    @files = grep(/\.out/ , @files);

    closedir(DIR);

    foreach my $file (@files)
    {
        if ( -z $directory.$file )
        {
            next;
        }
        ProcessData($directory.$file);
    }

}
else
{
    print STDERR "unable to open current directory\n";
}

sub ProcessData
{
    my ($file) = @_;

    if(open(FILE , $file))
    {
        my @lines = <FILE>;
        my $lines =~ s/\,//g;
        my @fields = split(/\s+/,$lines[1]);

        print "$fields[1] $fields[2] $fields[3] $fields[4] $fields[5]\n";

        close FILE;
    }

    else
    {
        print STDERR "Can't open $file\n";
    }

我正在尝试将一组文件的第二行拆分为空格,删除所有逗号,然后打印一些字段。打印了正确的字段,但逗号仍然存在,我收到错误消息:Use of uninitialized value $lines in substitution (s///)。我是Perl的新手,对此非常困惑。任何帮助将非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

好的,你离我不太远。问题是你写了my $lines =~ s/\,//g;而不是$lines[1] =~ s/\,//g;

#!/bin/perl
use strict;
use warnings;

my $file = "input.txt";
open my $fh, "<", $file or die "$!";

my @lines = <$fh>;
$lines[1] =~ s/\,//g; # This is the line that needed to be fixed
my @fields = split('\s+', $lines[1]);
print "$fields[1] $fields[2] $fields[3] $fields[4] $fields[5]\n";
close $fh;

输出:

  

$ cat input.txt
  UniProtAC,Nat,Resnum,Mut,Prediction,Confidence
  AvrgALL:P06132,ARG,332,HIS,PD,0.62
  $ perl sub.pl
  P06132 ARG 332 HIS PD

我想指出的另一件事是:What's the best way to open and read a file in Perl?。使用open的3参数形式通常更好,使用词法文件句柄也是如此。