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]";
}
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]";
}
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";
}
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
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";
}