What does this perl script do?

I was sorting through a Perl script written by someone else and I am not too familiar with Perl, so can someone tell me what 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 at the beginning of the program after installing $filename with receiving command line arguments

The file format passed to this script is

 [ { "Key1" => "val1", "key2" => " "A", }, { "Key3" => "val2", "key4" => " "B", }, ] 
+4
source share
3 answers

He does this:

  • my $ref = do($filename) executes Perl code in a file named $filename ( ref ) and assigns $ref value of the last command in the file
  • $ref != 0 or die … intended to be canceled if the last command in $filename not successful (see comments below for a discussion)
  • @ varLines=@ {$ref}; assumes $ref is an array reference and initializes @varLines contents of this array
  • foreach $ord (@varLines) { … } executes some code for each element of the array, calling each of $ord for the duration of the loop

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

+12
source

The do command will execute the given file name as a Perl script and return the value of the last expression to the file. So, I assume that the file on which the action is performed returns a reference to the array.

The next block just iterates over the elements in the returned array.

+4
source

perldoc -f do

  • do EXPR

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

     do 'stat.pl'; 

    just like

     eval `cat stat.pl`; 

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

In this case, it seems that the contents of $filename expected to produce a result of something like

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

and the foreach will process each element.

+2
source

All Articles