I'm sorry I'm not good at English. :-)
foreach and map functions show the same result when an array has no
gap.
@array = (1, 2, 3, 4);
foreach (@array) {
$_ *= 10
}
# now, $array = (10, 20, 30, 40)
@array = (1, 2, 3, 4);
map { $_ *= 10 } @array;
# now, $array = (10, 20, 30, 40)
However, if an array contains a gap...
1 $array1[0] = 0;
2 $array1[9] = 9; # now $array1 = (0, undef,
undef, ... , 9);
3 print "@array1", "\n"; # 0 "" "" ... "" 9
4 foreach (@array1) {
5 $_ *= 10 # $array1 = (0, 0, 0, ... , 90)
6 }
7 print "@array1", "\n"; # 0 0 0 ... 0 90
8
9
10 $array2[0] = 0;
11 $array2[9] = 9;
12 print "@array2", "\n"; # 0 "" "" ... "" 9
13 map { $_ *= 10 } @array2; # ERROR!!!!!!
14 print "@array2", "\n";
line 1-7 work well, but using map, line 13 reports an error:
Modification of a read-only value attempted at t2.pl line 13.
Before line 13, line 12 prints the intervening elements, treating
undef as null string. Then why does line 13 make such error? Is it a
bug? or...?
####
picard:~ [13:47:28]$ perl -le '$x[5]=5; $_*=10 for @x; print "@x"'
0 0 0 0 0 50
picard:~ [13:47:32]$ perl -le '$x[5]=5; $_*=10 for grep 1, @x; print "@x"'
Modification of a read-only value attempted at -e line 1.
picard:~ [13:47:36]$ perl -le '@x=0..5; $_*=10 for grep 1, @x; print "@x"'
0 10 20 30 40 50
####
my @array;
$array[0] = 0;
$array[9] = 9;
####
SV = NULL(0x0) at 0x182d528
REFCNT = 1
FLAGS = ()
####
SV = PVLV(0x18b3164) at 0x182d510
REFCNT = 2
FLAGS = (GMG,SMG)
IV = 0
NV = 0
PV = 0
MAGIC = 0x18e3474
MG_VIRTUAL = &PL_vtbl_defelem
MG_TYPE = PERL_MAGIC_defelem(y)
TYPE = y
TARGOFF = 1
TARGLEN = -1
TARG = 0x1b8d8e4
SV = PVAV(0x22b4c4) at 0x1b8d8e4
REFCNT = 3
FLAGS = (PADBUSY,PADMY)
IV = 0
NV = 0
ARRAY = 0x20093bc
FILL = 9
MAX = 11
ARYLEN = 0x0
FLAGS = (REAL)
Elt No. 0
SV = IV(0x1823db8) at 0x1ffca94
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 0
Elt No. 1
Elt No. 2
Elt No. 3
####
SV = NULL(0x0) at 0x224b30
REFCNT = 2147479514
FLAGS = (READONLY)
####
picard:~ [13:53:28]$ cat inc.pl
#!/usr/bin/perl -l
use strict;
use warnings;
sub inc { $_++ for @_ }
my @array;
$array[1]=666;
inc @array;
print "@array";
__END__
picard:~ [13:53:31]$ ./inc.pl
Use of uninitialized value in join or string at ./inc.pl line 11.
667
####
picard:~ [14:15:22]$ cat inc.pl
#!/usr/bin/perl
use strict;
use warnings;
use Devel::Peek 'Dump';
sub inc { $_++ for @_; Dump $_[0] }
my @array;
$array[1]=666;
inc @array;
Dump $array[0];
__END__
picard:~ [14:15:35]$ ./inc.pl
SV = PVNV(0x8152908) at 0x819ab20
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 1
NV = 0
PV = 0
SV = NULL(0x0) at 0x819ab20
REFCNT = 1
FLAGS = ()