Easiest way to open a text file and read it into an array with Perl

前端 未结 8 1633
星月不相逢
星月不相逢 2020-12-14 02:46

Adding a standard Perl file open function to each script I have is a bit annoying:

sub openfile{
    (my $filename) = @_;
    open FILE,\"$filename\" or die          


        
8条回答
  •  既然无缘
    2020-12-14 03:01

    You have several options, the classic do method:

    my @array = do {
        open my $fh, "<", $filename
            or die "could not open $filename: $!";
        <$fh>;
    };
    

    The IO::All method:

    use IO::All;
    
    my @array = io($filename)->slurp;
    

    The File::Slurp method:

    use File::Slurp;
    
    my @array = read_file($filename);
    

    And probably many more, after all TIMTOWTDI.

提交回复
热议问题