tags:

views:

193

answers:

3

I was going over a Perl script written by someone else and I am not too familiar with Perl so could someone let me know what do the first three lines do?

my $ref = do($filename);
$ref != 0 or die "unable to read/parse $filename\n";
@varLines=@{$ref};
foreach $ord (@varLines)
{
    # code here
}

This is in the beginning of the program after the $filename is set with getting the commandline arguments

The format of the file being passed to this script is

[
  {
    "Key1" => "val1",
    "key2" => " "A",
  },
  {
    "Key3" => "val2",
    "key4" => " "B",
  },
]
+4  A: 

The do command will execute the given file name as a Perl script and return the value of the last expression in the file. So, I'm guessing the file being acted upon here returns a reference to an array.

The next block simply iterates over the elements in that returned array.

jheddings
Didn't know that. Thanks!
Geo
+2  A: 

perldoc -f do

  • do EXPR

    Uses the value of EXPR as a filename and executes the contents of the file as a Perl script.

    do 'stat.pl';
    

    is just like

    eval `cat stat.pl`;
    

    except that it's more efficient and concise, keeps track of the current filename for error messages, searches the @INC directories, and updates %INC if the file is found. See "Predefined Names" in perlvar for these variables. It also differs in that code evaluated with do FILENAME cannot see lexicals in the enclosing scope; eval STRING does. It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop.

In this case, it appears that it is expected that the contents of $filename give a result of something like

[
  "line1",
  "line2",
  "line3",
]

and the foreach loop will then process each item.

ephemient
+10  A: 

It does this:

  • my $ref = do($filename) executes the Perl code in the file whose name is $filename (ref) and assignes to $ref the value of the last command in the file
  • $ref != 0 or die … is intended to abort if that last command in $filename wasn't successful (see comments below for discussion)
  • @varLines=@{$ref}; assumes that $ref is a reference to an array and initialises @varLines to the contents of that array
  • foreach $ord (@varLines) { … } carries out some code for each of the items in the array, calling each of the $ord for the duration of the loop

Critically, it all depends on what is in the file whose name is in $filename.

Tim
Your second bullet isn't quite right. $ref is undef if $filename could not be found or it couldn't be compiled. The check should really be changed to "defined $ref or ...".
jamessan
Good points, now incorporated. Thank you. :-)
Tim