user3707434
user3707434

Reputation: 15

When is $example[n] undef for @example in Perl?

A consistent problem I run into when scripting is the return of use of uninitialized value "x" in 'y'. This most frequently occurs when I attempt to take a specific value from a previously defined array. An example can be found below:

my $in = $ARGV[0];

open $in, '<', 'input.txt';

for my $i ( 1 .. 10 ) {
    my @line = ( split ' ', <$in> );
    if ( $line[0] ne qw(Temperature) ) {
        next;
    } else {
        print "$line[1]\n";
    }
}

I have determined that the data is being input into the @line array through a print command, but cannot understand why I am unable to call the first and second items within that array.

EDIT: Input file format: Average Values for the last 100 out of 100 Dynamics Steps

Simulation Time              0.1000 Picosecond
Total Energy                59.7313 Kcal/mole   (+/-   1.9942)
Potential Energy           -68.6523 Kcal/mole   (+/-   3.9487)
Kinetic Energy             128.3835 Kcal/mole   (+/-   3.8432)
Intermolecular            -199.2242 Kcal/mole   (+/-   1.7462)
Temperature                  124.12 Kelvin      (+/-     3.72)

Repeat x10000.

Upvotes: 1

Views: 66

Answers (2)

Neil H Watson
Neil H Watson

Reputation: 1070

You print the line, but you don't know that the array is defined.

my @line = ( split ' ', <$in> );
next unless ( @line )
if ( $line[0] ne qw(Temperature) ) {
        next;
    } else {
        print "$line[1]\n";
    }

Miller's answer is also valid; your use of the file handle is non-conventional.

Upvotes: 0

Miller
Miller

Reputation: 35208

Don't assume that your file will always have 10 lines of input. Instead iterate on the file.

use strict;
use warnings;
use autodie;

#my $in = $ARGV[0];

open my $fh, '<', 'input.txt';

while (my $line = <$fh>) {
    last if $. > 10;

    my @cols = split ' ', $line;

    next if $cols[0] ne 'Temperature';

    print "$cols[1]\n";
}

Upvotes: 3

Related Questions