The problem is that your array @xyz will only ever contain one value, since your for loop takes one array element at the time. Then you assign the value of a single scalar through a map statement, to an array declared inside the for-loop, which means the array will be out of scope when the loop is done and no values are ever saved between loop iterations.
my @abc = ('1234.txt', '2345.txt', '3456.txt', '4567.txt');
foreach my $abc(@abc) { # using one array element at the time
my @xyz = map(m/(\d*).txt/, $abc); # single string, never saved
print "@xyz\n"; # only prints one value
}
Since @xyz only contains one value, it makes no difference if you print the entire array, or just the first element.
If you want this to work, you have to move the array outside the loop, and use push, not assignment = (the latter will overwrite). And remove the map statement, as it is redundant for single strings. Also, put the print statement outside the loop, or we will print some values multiple times.
my @abc = ('1234.txt', '2345.txt', '3456.txt', '4567.txt');
my @xyz; # declare outside loop
foreach my $abc(@abc) {
push @xyz, $abc =~ m/(\d*).txt/;
}
print "@xyz\n"; # print only after all values have been collected
But this is not the best way to do it. The for-loop is redundant if we use map. Both for and map loop around the values in a list/array, so doing it twice serves no purpose in this case. The solution, as has already been given by Wes and in comments:
my @abc = ('1234.txt', '2345.txt', '3456.txt', '4567.txt');
my @xyz = map { m/(\d+).txt/ } @abc;
print "@xyz\n";
Also, you should use \d+ when collecting numbers, as otherwise you will get empty string false positives for some strings. For example, the string foo.txt would return the empty string "". If you expect the whole file name to be numbers you should use a beginning-of-line anchor: /^(\d+)\.txt/. Also, period . should be escaped, because it is a regex meta character.
my @xyz = map { /(\d+)\.txt$/ } @abc;instead of the for loopmapandforare loops, so you are looping twice around the values, but still just doing them 1 by 1, which is why the output is the same. And you are assigning the array inside the for-loop, so they will not be saved into the array anyway.