in reply to Re: Determine whether file is dos or unix format
in thread Determine whether file is dos or unix format

The snippet

open FILE, 'test_file.txt' || die "$!\n"; my $text = join( '', @{ [ <FILE> ] } ); close FILE;
  1. will never die on error,
  2. is inefficient,
  3. uses a global variable (FILE),
  4. would be safer if the 3 parameter open was used, and
  5. will not work on a Windows (and other?) machines without binmode.


It will never die because "||" has higher precedence than ",".

open FILE, 'test_file.txt' || die "$!\n";
means
open FILE, ('test_file.txt' || die "$!\n");
so use
open FILE, 'test_file.txt' or die "$!\n";
or
open(FILE, 'test_file.txt') || die "$!\n";


It is ineffecient you create an anonymous array and immediately dereference it.

join( '', @{ [ <FILE> ] } );
is equivalent to
join( '', <FILE> );

It is also ineffecient because join is slower and less memory efficient than undefining $/.

my $text = join( '', <FILE> );
is equivalent to the more efficient
my $text; { local $/; $text = <FILE>; }


So you end up with

my $text; { open(my $fh, '<', 'test_file.txt') or die("Unable to open input file: $!\n"); binmode($fh); local $/; $text = <$fh>; }

Replies are listed 'Best First'.
Re^3: Determine whether file is dos or unix format
by blazar (Canon) on Nov 29, 2005 at 08:16 UTC
    I second of all of what you wrote in this detailed and precise post. Only I feel like adding for completeness that re binmode, an alternative is given by layers/disciplines, and an IMHO clear one in terms of readability intelligibility. And I'm keen on do too, so all in all I'd rewrite the above like
    my $text = do { open my $fh, '<:raw', 'test_file.txt' or die "Unable to open input file: $!\n"; local $/; <$fh>; };

      my $text = do { ... };
      is slower than
      my $text; { $text = ...; }
      and requires twice as much memory.

      I agree that it looks nicer, and I usually use it for that reason.