Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
A long time ago, i suggested a rather drawn out way to transform a 1-D array into a 2-D array: (jeffa) Re: Structure for nested html::template loops. It uses autovivification to know which row to add the current piece of data to. Upon showing this to one of my college professors, he showed me a much simpler way to achieve the same results in Python, using the range built-in function.

That function takes 3 args, the first two are the start and stop points ... and if we stop right there then this function is complete "word-candy", as the dot dot operator already does this. But, the 3rd argument is the 'step', which allows for some cool stuff:

use Data::Dumper; my $step = 5; my @array = ('a'..'z'); print Dumper [ map[ @array[$_..$_+$step-1] ], range(0,$#array,$step) ];
This allows you to create a 2-D array from a 1-D array, 'folded' where ever you like. At the end, if there are no more element to stuff in the last row, the correct amount of 'undef' values will be pushed.

Now all we need is the ability to handle 'lazy lists' like Python's xrange. ;)

(and a big thanks to merlyn for reviewing this and improving it)

UPDATE: ack ... rob_au already posted something similar: Stepping through an array. (he also points out Abigail-II's solution - no grep needed!)

# usage: my @AoA = range($start,$stop[,$step]); sub range {grep!(($_-$_[0])%($_[2]||1)),$_[0]..$_[1]}

In reply to emulate Python's range function by jeffa

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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-03-29 00:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found