Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

array push fails

by rsFalse (Chaplain)
on Aug 14, 2017 at 18:10 UTC ( [id://1197370]=perlquestion: print w/replies, xml ) Need Help??

rsFalse has asked for the wisdom of the Perl Monks concerning the following question:

Hello,

I've tried to use push() on array, but program tells me an error.
#!/usr/bin/perl use warnings; use strict; my @numbers = 6 .. 9; my @odd = ( 1, 5, 3 ); my @even = ( 4, 10 ); $\ = $/; $, = ' '; map { print( ( $_ % 2 ? @odd : @even ), "+$_" ) } @numbers; map { push( ( $_ % 2 ? @odd : @even ), "+$_" ) } @numbers;
OUTPUT:
4 10 +6 1 5 3 +7 4 10 +8 1 5 3 +9 Not an ARRAY reference at ./push_fail.pl line 13.
How can I correctly push using "?:" operator?

Replies are listed 'Best First'.
Re: array push fails
by NetWallah (Canon) on Aug 14, 2017 at 18:26 UTC
    map { push( @{$_ % 2 ? \@odd : \@even }, "+$_" ) } @numbers;
    On my (perl 5.24) system, your original code says:
    Experimental push on scalar is now forbidden at pf.pl line 13, near "" ++$_" ) "
    Update: BTW - "map" is not the best choice for this code, because you are throwing away the result of the map.

    Preferred, and more concise:

    push( @{$_ % 2 ? \@odd : \@even }, "+$_" ) for @numbers;
    Then there is room for optimization:
    my @evenodd = (\@even, \@odd); push( @{$evenodd[$_ % 2]}, "+$_" ) for @numbers;

                    All power corrupts, but we need electricity.

Re: array push fails
by Cristoforo (Curate) on Aug 14, 2017 at 18:39 UTC
      Thank you guys for answers and links! ;)
Re: array push fails
by Mr. Muskrat (Canon) on Aug 14, 2017 at 18:37 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1197370]
Approved by Mr. Muskrat
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-25 07:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found