Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: How Perl can push array into array and then how retrieve

by kcott (Archbishop)
on Nov 25, 2021 at 04:30 UTC ( [id://11139098]=note: print w/replies, xml ) Need Help??


in reply to How Perl can push array into array and then how retrieve

I'm guessing somewhat regarding what you want to achieve.

Always put strict and warnings at the top of your code. In this instance, that would have alerted you to the fact that there was something wrong with $f.

I was unsure why you wanted to increment $i inside the loop. In my version, I changed $i+=2 to $i+2.

Here's a couple of ways of doing what I think you want:

#!/usr/bin/env perl use strict; use warnings; my @f; # Modification of your code for my $i (0..2) { my @e = ($i+2, $i+1); push @f, [@e]; } # A more succinct way to achieve it for my $i (3..5) { push @f, [$i+2, $i+1]; } # For demo purposes use Data::Dump; dd \@f;

Output:

[[2, 1], [3, 2], [4, 3], [5, 4], [6, 5], [7, 6]]

See also: "perlintro: Arrays"; "perldsc - Perl Data Structures Cookbook"; "perllol - Manipulating Arrays of Arrays in Perl".

— Ken

Replies are listed 'Best First'.
Re^2: How Perl can push array into array and then how retrieve
by kcott (Archbishop) on Nov 25, 2021 at 05:49 UTC

    Just as an afterthought, an even more succinct way is

    ... my @f; push @f, [$_+2, $_+1] for 0 .. 5; ...

    which produces identical output.

    — Ken

      Or:

      ... my @f = map [$_+2, $_+1], 0 .. 5; ...

        On the downside, this would probably take me longer to understand than kcott's code when coming back to it after a year. Your solution is probably a lot faster, but for some strange reason i can never really wrap my head around map() (and similar functions) without looking at the perldoc.

        perl -e 'use Crypt::Digest::SHA256 qw[sha256_hex]; print substr(sha256_hex("the Answer To Life, The Universe And Everything"), 6, 2), "\n";'

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-03-28 08:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found