zen_27 zen_27 - 8 months ago 47
Perl Question

Why is Perl telling me that my array is undeclared when I have already declared it?

I have an input file that looks like this:

AC_000044.1_a_bothflanks_2kb_polyA.4 AAGTATAATAAAAAAAAAAAAGAAA 25 25 69646
AC_000044.1_ac_bothflanks_2kb_polyA.3 TATAATTAAAAAAAAAAAAAAAAAAAA 27 164 69642

5 pieces of information seperated by tabs. I want to take each number in the 5th tab and compare it to every number in the 4th tab, if it is less than or equal to that number that I would like it to return the data in the first tab.

Here is my code:

#! /usr/bin/perl -w
use strict;
use Cwd;

my $tab_input = $ARGV[0];
my $output = 'output.txt';
my (@trans_id, @seq, @length, @cum_length, @coord);

open (my $INPUT, "<$tab_input") or die "unable to open $tab_input\n";
open (my $OUTPUT, ">$output") or die "unable to open $output\n";

while (<$INPUT>) {

my @tabfile =split ("\t+",$_);
push @trans_id, $tabfile[0];
push @seq, $tab_file[1];
push @length, $tab_file[2];
push @cum_length, $tab_file[3];
push @coord, $tab_file[4];

for (@tabfile) {
if {$tabfile[3] < $tabfile [4]) {
print "$tabfile[0]\n" > $output;



close $output;
close $tab_input;
print "Tab file parsing complete.\n";

However, I get errors at line 22 (the if statement) saying that $coord and %cum_length requires explicit package name. I have already delcared the arrays at the top of the code. And why is it returning a % 'hash' symbol in the error code when I am only using arrays. Any ideas?

Answer Source

The errors that you describe aren't generated by that code. Here's a list of the problems that I can see

  • You have declared @tabfile but are using @tab_file

  • Your statement if {$tabfile[3] < $tabfile [4]) { has an opening brace instead of an opening parenthesis

  • Your statement print "$tabfile[0]\n" > $output should be

    print $OUTPUT "$tabfile[0]\n";
  • The same statement is missing a closing brace

  • close requires a file handle parameter, not a file name, so your statements close $output and close $tab_input should be close $OUTPUT and close$INPUT` respectively.

I think it should look more like this


use strict;
use warnings 'all';

open my $out_fh, '>', 'output.txt' or die $!;

while ( <> ) {

    my @fields = split;

    print $out_fh "$fields[0]\n" if $fields[3] < $fields [4];

print "Tab file parsing complete.\n";