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

前端 未结 8 1623
星月不相逢
星月不相逢 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:14

    For quick and dirty, I rather like the simplicity of mucking with @ARGV.

    # Ysth is right, it doesn't automatically die; I need another line.
    use 5.010;
    use strict;
    my @rows = do { 
        use warnings FATAL => 'inplace'; # oddly enough, this is the one. ??
        @ARGV='/a/file/somewhere';
        <>;
    };
    say q(Not gettin' here.);
    

    If perl* cannot open the file, it automatically dies.


    * - the executable, so please don't capitalize.

    0 讨论(0)
  • 2020-12-14 03:15

    You might also want to consider using Tie::File, particularly if you are reading larger files and don't want to read the entire file into memory. It's a core module. Also, please refer to perlfaq5.

    0 讨论(0)
提交回复
热议问题