user2638757
user2638757

Reputation: 11

I would like to set arrays indirectly in Perl

I have a file where every 4 lines there is a block of information. I have set up 4 arrays named @linearray1, @linearray2, @linearray3, @linearray4.

I also have a counter than gets incremented for every four lines called $lineno.

I would like to set the four arrays and then parse them out appropriately.

But rather than set them directly four times I would like to do it in one line and then just check $lineno at 5 to do the rest.

So rather than writing out : @linearray1=split(",",$_)

I want to do something like: @linearray.$lineno=split(",",$_);

Upvotes: 1

Views: 73

Answers (2)

Dan
Dan

Reputation: 10786

You can use a variable as the name of a variable (or part of that name) in Perl. The syntax you're trying to find is:

@{'linearray'.$lineno} = split(',', $_);

Since split will default to $_ in the absense of a second arg, and for the sake of a complete answer, you can do:

foreach $lineno (1..4) @{'linearray'.$lineno} = split ',';

Don't get confused by the {} in that syntax, there's no hash dereference going on, but when you have a sigil followed immediately by an open brace, the outcome of the expression in the braces is used as the name of the variable.

Is there a reason you can't use a two-dimensional array, like @{$linearray[$lineno]}? That's considered to be cleaner, and is almost certainly a little faster.

Upvotes: -1

ikegami
ikegami

Reputation: 386676

Don't generate variable names.

Instead, use

@{ $lines[$lineno] } = split /,/;

Or more directly:

$lines[$lineno] = [ split /,/ ];

Or even

push @lines, [ split /,/ ];

You can access elements using

for my $lineno (0..$#lines) {
   say join ', ', @{ $lines[$lineno] };
}

or

for my $line (@lines) {
   say join ', ', @$line;
}

Remember to always use use strict; use warnings;!

Upvotes: 4

Related Questions