Dear PerlMonks,

I'm translating some python(2) code into perl, and I'm hoping there are some bilingual sorts who can help. (It's an interesting poetry writing program that I don't think I can begin to understand until I at least have it in a language I understand. Plus I'm hoping it'll run faster in Perl. Otherwise I wouldn't be undertaking this labor of love. :-p )

One of the biggest headaches is translating Python's list range expressions into equivalent Perl array expressions. In Python you can write:

a = [ 'a','b','c','d','e','f','g' ] a[:3] # abc a[:-3] # abcd a[3:] # defg a[-3:] # efg
In Perl, using List::Util qw/head tail/, the equivalent is:
my @a = qw/a b c d e f g/; # python a[:3] = 'abc' (ie. select first 3) say join( '', head( 3, @a)) . " should be abc"; # python a[:-3] = 'abcd' (ie. omit last 3) say join( '', head( -3, @a)) . " should be abcd"; # except when -0! # python a[3:] = 'defg' (ie. omit first 3) say join( '', tail( -3, @a)) . " should be defg"; # except when -0! # python a[-3:] = 'efg' (ie. select last 3) say join( '', tail( 3, @a)) . " should be efg";
Of course, most of the time the code contains a variable, not a hard-coded 3. And then my solution breaks on head(-$p, @a) and tail(-$p, @a) when $p is 0.

Is there a CPAN module that might support python-like specification of array ranges in a concise manner?


In reply to Converting python list range expressions to perl by ibm1620

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.