Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^3: Array wierdness

by pryrt (Abbot)
on Apr 25, 2022 at 15:34 UTC ( [id://11143276]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Array wierdness
in thread Array wierdness

FWIW, assigning the numbers to the arrays in separate lines makes no difference.

This is because your code's comments are wrong:

# fill two 25 x 25 arrays with zeros, then modify a couple of cells my @PP = my @OO = (1..25);

This does not create 25x25 arrays, this creates 1x25 arrays.

Below shows a 1x25 (what you have) vs a 2x5:

use strict; use warnings; use Data::Dump; my @one_by_twentyfive = (1..25); my @two_by_five = ([1..5],[1..5]); dd \@one_by_twentyfive; dd \@two_by_five; __END__ [1 .. 25] [[1 .. 5], [1 .. 5]]

or this one populates a 25x25 array, then overrides 3 slots:

Replies are listed 'Best First'.
Re^4: Array wierdness -- initialize AoA
by Discipulus (Canon) on Apr 26, 2022 at 09:04 UTC
    Hello,

    you can also initialize an ArrayOfArrays setting default values using x (repetition operator in list context) like in:  @aoa = ([( 1 ) x 3]) x 3

    L*

    PS I evidently need more coffeine this morning.. see below

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

      That's usually not what you want: that'll give you three copies of the same arrayref, so if you later modify an element in one row it'll modify it in all rows:

      % perl -wle '@aoa = ([(1) x 3]) x 3; $aoa[1][2] = 3; print "@$_" for @ +aoa' 1 1 3 1 1 3 1 1 3

      If you want each element to be independent, a typical approach is to pass it through map:

      % perl -wle '@aoa = map [(1) x 3], 1..3; $aoa[1][2] = 3; print "@$_" f +or @aoa' 1 1 1 1 1 3 1 1 1

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11143276]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2024-04-19 15:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found