CheeseConQueso
CheeseConQueso

Reputation: 6041

Can someone explain this Perl code snippet?

This little piece of code has been a staple in a bunch of my scripts, but I took the syntax from another working script that someone else wrote and adapted it to fit my needs. I'm not even sure that the syntax used here is the best or most common way to open a file handler either.

The code is:

$fh = \*STAT_FILE;
open ($fh,">>".$stat_file) or die "Can't open $stat_file: $!\n";
my $print_flag = ( -z $stat_file );

I don't fully understand the first line and also the last line of the code above. Specifically, \*STAT_FILE and -z, respectively.

I know that, for the most part, the second line will open a file for appending or quit and throw an error. But again, I don't understand what purpose the $! serves in that line either.

Can someone explain this Perl code, line-by-line, to me in pseudo? Also, if the method above is not the preferred method, then what is?

Thanks in advance

Upvotes: 1

Views: 239

Answers (2)

runrig
runrig

Reputation: 6524

Before perl 5.6, file handles could only be globs (bare words) or references to globs (which is what \*STAT_FILE is). Also, it's better to use 3-argument open (See the docs. Also see perlopentut). So you can now do:

open(my $fh, ">>", $stat_file) or die "Failed to open $stat_file: $!";

and forget about \*STAT_FILE.

-z is one of the file test functions (and takes a file name or file handle as an argument) and tests to see if the file has zero size.

$! is one of the Special Variables and contains the most recent system error message (in this case why you can not open the file, perhaps permission issues, or a directory in the path to the file does not exist, etc.).

You should learn to use perldoc, all of this is in perldoc:

perldoc perlfunc (specifically perldoc -f open and perldoc -f -X)

perldoc perlvar

Upvotes: 11

Daniel
Daniel

Reputation: 1357

The first row assign to the variable a reference (the backslash sign) to the typeglob (a fullsymbol table entry) STAT_FILE. This has been a quite idiomatic perl construct to pass filehandles as reported, just to name it, in the Larry Wall "Programming perl". The $! variable contains the error message reurned by the operating system.

So the whole meaning is:

  • line 1. put in the $fh variable a filehandle;
  • line 2. Open for append the file reporting the system message error should a fault happens;
  • line 3. Set a flag variable warning if the file has zero length

Upvotes: 3

Related Questions