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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.