Thomas Anowez
Thomas Anowez

Reputation: 91

Insert array value into $scalar - Perl

How could i assign a specific array value into $skip? I would start to read from a.txt or b.txt from a specific line (88 for a.txt and 64 for b.txt)

#!/usr/bin/perl
# Libraries
use strict;
use warnings;

# Main script
my @filename = ('a.txt', 'b.txt');
my @nrows = ('88', '64');

foreach my $file_input(glob("*.txt")) {
    open my $fh, '<', $file_input or die "can't read open $IN_FILE";
    for my $i (0 .. $#nrows) {
        if ( $file_input eq $filename[$i] ) {
            my $skip = $nrows[$i];
        }
    }
    $/ = "\n\n";  # record separator
    while( <$fh> ) {
    next unless '$skip' .. undef;
    my @lines = split /\n\n/;
    **... some manipulations ...**
}
close ($fh);
}

I Receive following error:

Use of uninitialized value $skip in concatenation (.) or string at ./exercise.n24.pl line 14, <$fh> chunk 11.

I've made a lot of test in last 4 hours, and I don't understand where I'm wrong

Upvotes: 2

Views: 225

Answers (2)

beasy
beasy

Reputation: 1227

The error you're getting is because in your code, you're trying to use $skip outside the scope it was declared in.

But on a broader level, It seems like you just want to skip a certain number of lines depending on the filename. You should use a hash for that instead of parallel arrays.

use strict;    

my %lines_to_skip = (
    'a.txt' => 88,
    'b.txt' => 64
);

for my $file (glob("*.txt")) {
    my $skip = $lines_to_skip{$file};
    open my $fh, '<', $file;
    # local $/ = "\n\n"; # note that this would read the file in paragraph mode
    while (<$fh>) {
         next unless $. > $skip;
         # do something
    }
}

Upvotes: 1

Dave Cross
Dave Cross

Reputation: 69224

I can see a couple of obvious errors here.

You declare $skip in a block that immediately ends.

if ( $file_input eq $filename[$i] ) {
    my $skip = $nrows[$i];
}

So you can never see the value of $skip.

Then, when you're trying to access $skip, you put it in single quotes. And variables don't expand in single quotes, so Perl just sees it as the five characters $, s, k, i and p.

But I don't think either of those explain the error you're seeing. Which line in your sample code is line 14.

It's far more useful to us if you give us a code sample that we can run.

I'd suggest an alternative approach, but I'm afraid it's really not clear what you're trying to do.

Upvotes: 3

Related Questions