This does what you want in a one liner. The loop is a little easier to understand if you are unfamiliar with map but they are essentially identical.
I have also shown you how to make your data access a lot less rigid. This code does not care about the structure of your 2D array which has been made irregular.
Not sure what you mean by access a 2D array as 1D. Do you want to flatten it into a list? I have coded that for you. Otherwise it is a 2D structure.
tachyon
#!/usr/bin/perl -w use strict; # here we have an irregular sized 2D array my @array = ( [1],[2,2],[3,3,3],[4,4,4,4] ); my $all ='42'; # this sets all elements to $all for (@array) { @$_ = ($all) x @$_; } # this also sets all elements to $all # map is just the loop above in short form map{ @$_ = ($all) x @$_ }@array; # this prints the entire structure for (@array) { for (@$_) { print "-",$_; } print"\n"; }
Explanation. $_ is magical. When we loop over @array each element is aliased to $_ in turn if we modify $_ we modify the actual element @$_ derefs our array elements in list context and allows us to modify them @$_ in scalar context gives the number of elements thus the polymorphic behaviour in this example
If you want to flatten this 2D array into a 1D array this code does that
map{ push @list, @$_ }@array; print "@list";
In reply to Re: setting multidimensional array values
by tachyon
in thread setting multidimensional array values
by perchance
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |