是否有更好的方法来编写此代码以避免冗余?

时间:2014-06-17 09:12:29

标签: perl

我在程序中有一段代码,它接受来自管道的GNU样式输入(这是一个文件名列表)。如果STDIN不包含数据,我需要接受来自包含文件名的预定文本文件的输入。

我发现自己需要编写冗余代码。是否可以简化这段代码以避免冗余?

sub downloadlinkgen {
    my $fh;
    print "Printing links\n";
    if ($getfilelist==1) {
        open $fh, '<', "fuzzyfile" or die $!;
        while (<$fh>) {
            chomp ($_);     
            (my $fname,my $path, my $suffix) = fileparse($_);
            my ($name, $ext) = $fname =~ /(.*)\.(.*)/;      
            my $newfile=$path.$name.".$ext";
            $newfile =~ s/\s/%20/g; 
            $newfile =~ s/\/root/http:\/\/myip/;        
            print $newfile."\n";        
        }
    } else {        
        while (<>) {
            chomp ($_);     
            (my $fname,my $path, my $suffix) = fileparse($_);
            my ($name, $ext) = $fname =~ /(.*)\.(.*)/;      
            my $newfile=$path.$name.".$ext";
            $newfile =~ s/\s/%20/g; 
            $newfile =~ s/\/root/http:\/\/myip/;        
            print $newfile."\n";        
        }
    }
}

3 个答案:

答案 0 :(得分:4)

是的,只需将默认的ARGV文件句柄打开文件:

sub downloadlinkgen {
    @ARGV = 'fuzzyfile' if $getfilelist == 1;
    print "Printing links\n";
    while (<>) {
        chomp ($_);     
        (my $fname,my $path, my $suffix) = fileparse($_);
        my ($name, $ext) = $fname =~ /(.*)\.(.*)/;      
        my $newfile=$path.$name.".$ext";
        $newfile =~ s/\s/%20/g; 
        $newfile =~ s/\/root/http:\/\/myip/;        
        print $newfile."\n";        
    }
}

答案 1 :(得分:2)

sub downloadlinkgen {

  # default file handle  
  my $fh = \*ARGV;
  print "Printing links\n";
  if ($getfilelist==1) {
    open $fh, '<', "fuzzyfile" or die $!;
  }

  while (<$fh>) {
    chomp ($_);   
    (my $fname,my $path, my $suffix) = fileparse($_);
    my ($name, $ext) = $fname =~ /(.*)\.(.*)/;    
    my $newfile=$path.$name.".$ext";
    $newfile =~ s/\s/%20/g; 
    $newfile =~ s/\/root/http:\/\/myip/;    
    print $newfile."\n";    
  }
}

来自perldoc -f readline

  

从文件句柄中读取,其类型包含在EXPR中(如果未提供EXPR,则来自* ARGV)

所以\*ARGV是对从<>阅读时使用的文件句柄的引用,在这两种情况下都可以使用$fh

答案 2 :(得分:1)

即使你不了解ARGV,你也可以做这样简单的事情:

sub downloadlinkgen {
    my $fh;
    print "Printing links\n";
    if ($getfilelist==1) {
        open $fh, '<', "fuzzyfile" or die $!;
        while (<$fh>) {
            process_line($_);     
        }
    } else {        
        while (<>) {
            process_line($_);       
        }
    }
}

sub process_line {
    my $line = shift;

    chomp ($line);     
    (my $fname,my $path, my $suffix) = fileparse($line);
    my ($name, $ext) = $fname =~ /(.*)\.(.*)/;      
    my $newfile=$path.$name.".$ext";
    $newfile =~ s/\s/%20/g; 
    $newfile =~ s/\/root/http:\/\/myip/;        
    print $newfile."\n";  
}