Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Problem creating array

by Unforgiven (Hermit)
on Sep 16, 2009 at 14:26 UTC ( [id://795629]=note: print w/replies, xml ) Need Help??


in reply to Problem creating array

I just used a foreach, because the x looked to be related to the problem, and it was the first and simplest thing that came to mind. You could do it shorter and more elegantly, but this works and is probably a little easier to read if you're still learning a bit.
my @count = (1,3,1,1,1,1,1,2,1,1,3,2); my @result; for (my $i=0; $i <= $#count; $i++) { foreach (1 .. $count[$i]) { push(@result, $i); } } print "\@count: @count\n"; print "\@result: @result\n";

Replies are listed 'Best First'.
Re^2: Problem creating array
by AnomalousMonk (Archbishop) on Sep 16, 2009 at 16:56 UTC
    The shorter, more elegant approach involves the use of the map built-in. You (Subop) don't need it right now, but you should keep  map in mind as you build your Perl skills.
    >perl -wMstrict -le "my @count = (1, 3, 1, 1, 1, 1, 1, 2, 1, 1, 3, 2); my @result = map { ($_) x $count[$_] } 0 .. $#count; print qq{@count}; print qq{@result}; " 1 3 1 1 1 1 1 2 1 1 3 2 0 1 1 1 2 3 4 5 6 7 7 8 9 10 10 10 11 11

      A slightly simpler map at the cost of declaring another scalar.

      $ perl -Mstrict -wle ' > my @count = ( 1, 3, 1, 1, 1, 1, 1, 2, 1, 1, 3, 2 ); > my $idx; > my @result = map { ( $idx ++ ) x $_ } @count; > print qq{@count}; > print qq{@result};' 1 3 1 1 1 1 1 2 1 1 3 2 0 1 1 1 2 3 4 5 6 7 7 8 9 10 10 10 11 11 $

      I hope this is of interest.

      Cheers,

      JohnGG

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-03-29 06:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found