代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

在Perl中使用文件句柄

  •  0
  • Aakash Goel  · 技术社区  · 14 年前

    我正在写一篇文章 comparefiles f1 )然后在另一个地方寻找( f2 )在正常情况下 O(n^2) 是的。

    sub comparefiles {
        my($f1, $f2) = @_;
        while(<f1>) {
            # reset f2 to the beginning of the file
            while(<f2>) {
            }
        }
    }
    
    sub someother {
        open (one, "<one.out");
        open (two, "<two.out");
        &comparefiles(&one, &two);
    }
    

    我有两个问题

    • 如何将文件句柄传递给子例程?在上面的代码中,我将它们用作标量。这样对吗?
    • f2层
    2 回复  |  直到 14 年前
        1
  •  8
  •   Toto    14 年前

    首先,每次编写脚本时都要从以下内容开始:

    use strict;
    use warnings;
    

    使用词汇文件句柄,打开三个参数并测试结果:

    open my $fh1 , '<' , $filename1 or die "can't open '$filename1' for reading : $!";
    

    comparefiles($fh1, $fh2);
    

    seek $fh, 0, 0;
    
        2
  •  2
  •   FMc TLP    14 年前

    如果文件足够小,可以放入内存中,您可以考虑将行存储在散列中,这样可以避免 O(n^2) 搜索。

    在现有方法的框架内,我建议不要嵌套文件读取循环——如果没有其他原因的话,可能是出于美观的考虑。相反,将内部循环放入子例程中。

    use strict;
    use warnings;
    
    # Works for 2 or more files.
    analyze_files(@ARGV);
    
    sub analyze_files {
        my @file_names = @_;
        my @handles = map { open my $h, '<', $_; $h } @_;
        my $fh = shift @handles;
    
        while (my $line = <$fh>) {
            my @line_numbers = map { find_in_file($_, $line) } @handles;
            print join("\t", @line_numbers, $line);
        }
    }
    
    # Takes a file handle and a line to hunt for.
    # Returns line number if the line is found.
    sub find_in_file {
        my ($fh, $find_this) = @_;
        seek $fh, 0, 0;
        while (my $line = <$fh>){
            return $. if $line eq $find_this;
        }
        return -1; # Not found.
    }