2

Consider these 2 snippets :

#!/bin/bash/perl
open(DATA,"<input.txt");
while(<DATA>)
{
  print($_) ;
}

and

$abcd = `cat input.txt`;
print $abcd;

Both will print the content of file input.txt as output

Question : Is there any standard, as to which one (backticks or native-method) should be preferred over the other, in any particular case or both are equal always??

Reason i am asking this is because i find cat method to be easier than opening a file in native perl method, so, this puts me in doubt that if i can achieve something through backtick way, shall i go with it or prefer other native ways of doing it!!

I checked this thread too : What's the difference between Perl's backticks, system, and exec? but it went a different route than my doubt!!

Community
  • 1
  • 1
NoobEditor
  • 15,563
  • 19
  • 81
  • 112

2 Answers2

7

Use builtin functions wherever possible:

  • They are more portable: open works on Windows, while `cat input.txt` will not.

  • They have less overhead: Using backticks will fork, exec a shell which parses the command, which execs the cat program. This unnecessarily loads two programs. This is in contrast to open which is a builtin Perl function.

  • They make error handling easier. The open function will return a false value on error, which allows you to take different actions, e.g. like terminating the program with an error message:

    open my $fh, "<", "input.txt" or die "Couldn't open input.txt: $!";
    
  • They are more flexible. For example, you can add encoding layers if your data isn't Latin-1 text:

    open my $fh, "<:utf8", "input.txt" or die "Couldn't open input.txt: $!";
    open my $fh, "<:raw", "input.bin" or die "Couldn't open input.bin: $!";
    

If you want a “just read this file into a scalar” function, look at the File::Slurp module:

use File::Slurp;

my $data = read_file "input.txt";
amon
  • 57,091
  • 2
  • 89
  • 149
3

Using the back tick operators to call cat is highly inefficient, because:

  1. It spawns a separate process (or maybe more than one if a shell is used) which does nothing more than read the file, which perl could do itself.

  2. You are reading the whole file into memory instead of processing it one line at a time. OK for a small file, not so good for a large one.

The back tick method is ok for a quick and dirty script but I would not use it for anything serious.

harmic
  • 28,606
  • 5
  • 67
  • 91
  • `You are reading the whole file into memory instead of processing it one line at a time` => didn't understood this, can u please explain??? – NoobEditor Mar 04 '14 at 10:05
  • In your first example, one line at a time is read and printed. In your second example the whole file is read into $abcd – harmic Mar 04 '14 at 10:09