0

I have N array and i want to print 1st elements of them in single for loop

my code:

@arr1=qw(1..5);
@arr2=qw(6..10);
...
@arrN=qw(...);
for($i=1;$i<=$N;$i++)
{
print "$arr[$i][0]";
}
5
  • 1
    Which language? Also, just put then in an array and iterate that instead. Commented Aug 24, 2014 at 6:30
  • i use perl. There is a syntax whixh i am not following here, like $arr({$i})[0] or similar. Commented Aug 24, 2014 at 6:32
  • 3
    Why are you using numbered arrays like that in the first place? Commented Aug 24, 2014 at 6:35
  • Thanks all, but your reply didnt solved my question, i figured it out myself Commented Aug 27, 2014 at 14:04
  • @arr1=(1..5); @arr2=(6..10); for($i=1;$i<=2;$i++) { print "${'arr'.$i}[0]\n"; } Commented Aug 27, 2014 at 14:04

3 Answers 3

5

When you find that you need to know the names of 0 .. N different variables. Its time to consider that you might be doing it wrong.

Arrays = list of 0 .. N values, can be sequential

Hash = list of 0 .. N named values

For your arrays, unless you actually want to be converting to strings, don't use qw() just use the bare ()

See solution below, you need an array of arrays: #!/usr/bin/perl

use strict;
use warnings;

my $n = 10;
my @nArrays;

#fills the nArrays list with array_refs
for my $num(0 .. $n){
  push @nArrays, [($num .. $num+5)]; 
}

#Print out the arrays, one per row, long way
for my $array (@nArrays){
  print $array->[0], "\n";
}
Sign up to request clarification or add additional context in comments.

Comments

2

If, contrary to all normal recommendations, you leave use strict; out of your script, you could use:

$N = 3;
@arr1 = (1..5);
@arr2 = (6..10);
@arr3 = (7..12);
@arrs = ("arr1", "arr2", "arr3");
for ($i = 0; $i < $N; $i++)
{
    print "$arrs[$i][0]\n";
}

Output:

1
6
7

This is absolutely not recommended, but it does work still (mainly for reasons of backwards compatibility).

With use strict; etc, you can use explicit references:

use strict;
use warnings;

my $N = 3;
my @arr1 = (1..5);
my @arr2 = (6..10);
my @arr3 = (7..12);
my @arrs = (\@arr1, \@arr2, \@arr3);
for (my $i = 0; $i < $N; $i++)
{
    print "$arrs[$i][0]\n";
}

Output:

1
6
7

On the whole, though, you would do better with a single array of arrays, perhaps like this:

use strict;
use warnings;

my $N = 3;
my @arr = ( [1..5], [6..10], [7..12] );
for (my $i = 0; $i < $N; $i++)
{
    print "$arr[$i][0]\n";
}

Output:

1
6
7

Comments

1

What you have in mind is called a symbolic reference, and generally not a good idea.

If the values of these variables belong together, there is already a data structure that is indexed by an integer: Use an array to hold them:

use strict;
use warnings;

my @arr = (
   [ 1 .. 5  ],
   [ 6 .. 10 ],
   # ...
   [ 1_000_000 .. 1_000_005 ],
);

for my $i (0 .. $#arr) {
   print $arr[$i][0], "\n";
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.