Please provide enough code to reproduce the problem. Are you
following recommended practice by using 'strict' to ensure there is
no typo in the array name? If so, the error isn't coming from the
code you posted. Also, note that your loop does not execute as
many times as there are elements in the array, since an array is
zero-based.
use strict;
use warnings;
my @test_num_tgb = qw/a b c d/;
for (my $j=1;$j<=$#test_num_tgb;$j++) {
print $test_num_tgb[$j];
print "\n";
}
As you can see, this skips printing the zeroeth element 'a'.
| [reply] [Watch: Dir/Any] [d/l] |
my @array_data = qw( 21 45 perl 28 monks);
foreach my $data (@array_data){
print $data,"\n";
}
Update:
However, if you want to iterate over the array, using the index of the array, Perl also does that for you very cleanly.
my @array_data = (21,45,'perl',28,'monks',' ','togo');
for my $num (0..$#array_data){
print $num,': ',$array_data[$num],"\n";
}
0: 21
1: 45
2: perl
3: 28
4: monks
5:
6: togo
Please, note that I used foreach and for inter-changeably.
And please don't forget that array index start from 0 and not 1, as used in your OP for loop.
Hope this helps
If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me
| [reply] [Watch: Dir/Any] [d/l] [select] |
Or a more Perlish way of using indexes (works only in a fairly recent version of Perl):
use Modern::Perl;
my @array = qw/een twee drie vier vijf zes zeven/;
for my $index (keys @array) {
say "$index: $array[$index]";
}
CountZero A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James My blog: Imperial Deltronics
| [reply] [Watch: Dir/Any] [d/l] |
| [reply] [Watch: Dir/Any] |
Another way, will only work for later versions of Perl
#!/usr/bin/perl
use strict;
my @arr = ("making","each","day","of","the","year","1");
while ( my($idx,$val) = each (@arr) ){
print "Index is: $idx. Value is: $val\n";
if($val =~ /^\d+$/){
do_my_function($val)
}
}
sub do_my_function {
my $v = shift;
print "We're in the sub for value: $v\n"
}
EDIT: Not sure what happened with my initial post but the comment I had about the regex was, as pointed out by AnomalousMonk, incorrect! | [reply] [Watch: Dir/Any] [d/l] |
>perl -wMstrict -le
"my $val = '222test001';
print $val =~ /^\d+$/ ? 'fire' : 'no match';
"
no match
| [reply] [Watch: Dir/Any] [d/l] |