Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Perl script achieve?

Tags:

perl

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",
  },
]
like image 596
randomThought Avatar asked Dec 02 '22 06:12

randomThought


1 Answers

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.

like image 82
Tim Avatar answered Jan 20 '23 10:01

Tim