Loading ...
Sorry, an error occurred while loading the content.

[PBML] Re: slurping a file

Expand Messages
  • David E Newman
    ... Kai, You could create a subroutine that takes a filename as an argument and returns an array. That s what I do. sub slurp_file_to_array { my $file_name =
    Message 1 of 2 , Feb 15, 2000
    • 0 Attachment
      On Mon, 14 Feb 2000, Kai Hintze wrote:

      >
      > Is there a one line way to slurp a file into an array?
      >
      > Instead of
      > open(FILE, "file") || warn "couldn't open file";
      > @array = <FILE>;
      > close(FILE);
      >
      > I would like to
      > @array = <"file">;
      >
      > I know, it's just a couple of lines, but Larry Wall himself says that
      > lazyness is a virtue. :)

      Kai,

      You could create a subroutine that takes a filename as an
      argument and returns an array. That's what I do.

      sub slurp_file_to_array {

      my $file_name = shift;
      my @array = ();

      open(FILE, $file_name) || die "couldn't open file $file_name : $! \n";
      @array = <FILE>;
      close(FILE) || die "couldn't close file $file_name : $! \n";

      return @array;

      }

      Then just call the subroutine from your program when you need it:

      my @array_file = slurp_file_to_array('myfile.txt');

      There is your one line.

      Dave Newman
    Your message has been successfully submitted and would be delivered to recipients shortly.