zara zara - 2 years ago 70
Bash Question

why this error? Use of uninitialized value in join or string at

When I run this script :

use warnings;
use strict;
use feature qw{ say };

my @header = split ' ', <>;
my $last = q();
my @keep;
for my $i (0 .. $#header) {
my ($prefix) = $header[$i] =~ /(.*)\./;
if ($prefix eq $last) {
push @keep, $i + 1;
$last = $prefix;
unshift @header, q();
say join "\t", @header[@keep];

while (<>) {
my @columns = split;
say join "\t", @columns[@keep];

Then I get this error:

Use of uninitialized value in join or string at./first.perl line 21, <> line 3986.

Can you guide me how I can get ride out of this error?
should I change something n may data file? Because when run this script in a small data file, I do not get error. But when I run it is my real data file, I get error.

Answer Source

At least one of the elements of the array slice @columns[@keep] is undef

You probably have a blank line at the end of your file. Take a look at line 3986 of your input file

I suggest you change your final loop to this, which skips lines that don't contain a non-space character

while (<>) {
    next unless /\S/;

    my @columns = split;
    my @kept = @columns[@keep];
    if ( grep { not defined } ) {
        warn "Malformed data at input file line $.\n";

    say join "\t", @kept;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download