REPORTER 22.1

Example perl Program to Read Variables File from REPORTER

Example perl program to read variables file from REPORTER

The following example shows how you could read this file.

Perl
# Skeleton REPORTER Perl script showing extraction of variables fed to program
# The variable file REPORTER generates will be the LAST argument
#
# Variables are stored in a hash '%vars', each entry in the hash contains
# {value} and {description}.
#
# e.g. If REPORTER has a variable 'FRED' with value '1' and description
# 'Example variable' you can get at the variable value and description using:
#
# $vars{FRED}->{value}
# $vars{FRED}->{description}
#
# Arguments
# =========
# 1: Variables file
#
# Miles Thornton 23/5/2002
#
%vars = ();

if ($#ARGV >= 0)
{
open (VAR, "< $ARGV[$#ARGV]") or die "Error: Cannot open variable file";

while ( <VAR> )
{
chomp;
&get_var_from_string($_);
}
}
else
{
die "Error: No variable file on the command line\n";
}

#########################################################
# START OF YOUR PROGRAM
#
# e.g. loop over variables and save them to a file

open (SAVE, "> varfile") or die "Error: Cannot open variables file";

foreach $var (sort keys %vars)
{
print SAVE "Variable $var value=$vars{$var}->{value} ",
"desc=$vars{$var}->{description}\n";
}

close (SAVE);

# END OF YOUR PROGRAM
#########################################################

exit;


# ===================
sub get_var_from_string
# ===================
#
# Tries to read a variable from the variable file
#
{
my $string = shift;

my ($var, $val, $desc);

if ($string =~ /VAR\s+(\w+)\s+
VALUE\s*=\s*['"](.*?)['"]\s*
DESCRIPTION\s*=\s*['"](.*?)['"]
/x)
{
$var = $1;
$val = $2;
$desc = $3;
}
elsif ($string =~ /VAR\s+(\w+)\s+
DESCRIPTION\s*=\s*['"](.*?)['"]\s*
VALUE\s*=\s*['"](.*?)['"]
/x)
{
$var = $1;
$val = $3;
$desc = $2;
}
elsif ($string =~ /VAR\s+(\w+)\s+
VALUE\s*=\s*['"](.*?)['"]
/x)
{
$var = $1;
$val = $2;
$desc = undef;

}

if ($var)
{
$var = uc($var);
$var =~ s/\s+/_/g;

if (exists $vars{$var})
{
$vars{$var}->{value} = $val;
$vars{$var}->{description} = $desc;
}
else
{
my $variable = {};
$variable->{value} = $val;
$variable->{description} = $desc;

$vars{$var} = $variable;
}
}
}