#tf.pl
#!/usr/local/bin/perl
use Util;
$file = shift;
$text = `cat $file`;
my @words = split_words ($text);
my @words = lc_words (@words);
my %count = count_hash(@words);
while (my ($w, $c) = each %count) {
print "$w\t$c\n";
$df{$w} = 1;
}
I came across that code on a website. On line 3 $file is given the name of the file that would have been supplied with the command line argument (correct me if I am wrong, I’m a Perl rookie)
On line 4 you see:
$text = `cat $file`;
I want to know what does this line do exactly? I know cat filename in shows you the content of the files in the terminal (again, correct me if wrong. Linux rookie too)
I asked this on IRC and someone said this was a bad way of doing something but I really want to know what this does more than knowing the better alternative of it
The backticks (so as to differentiate them from quotes
'or") run whatever they contain as an external application, then the assignment captures the output to the variable$text. The contents (inside the backticks) can be any runnable process:and so on.
It’s not usually a good idea since it ties the program to a specific operating system (those with a
catcommand in this case).That may not be a problem but you should be aware that it reduces portability.
There are perfectly acceptable ways to already get the contents of a file into a variable in Perl, one that will work across all platforms (
open,while <BLAH>, appending strings, andclose), such as this sample programxyzzy.plwhich reads itself in in two different ways (the first portable, the other not):which outputs: