Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Okay, took the hint and did it all with slices. Does this look right?
use v5.36; no warnings q/experimental/; # no warns about for-list sub range($aref, $start=undef, $end=undef) { if (!defined $start) { $start = 0; if ($end >= 0) { $end = $end - 1; } else { $end = $#$aref + $end; } } elsif (!defined $end) { $end = $#$aref; if ($start < 0) { $start = $#$aref + $start + 1 ; } } else { die "a[i:j] ranges not supported yet"; } print "\@a[$start .. $end] "; return [@$aref[$start .. $end]]; } my @a = qw/a b c d e f g/; my @tests = ( [3, undef, 'defg'], [0, undef, 'abcdefg'], [-3, undef, 'efg'], [undef, 3, 'abc'], [undef, 0, ''], [undef, -3, 'abcd'], ); for my ($i, $j, $answer) (map {@{$_}} @tests) { printf("a[%s:%s] -> ", $i // '', $j // ''); printf("range(a, %s, %s) -> ", $i // 'undef', $j // 'undef'); my $aref = range(\@a, $i, $j); my $join = join '', @$aref; printf("'$join', expecting '$answer'\n"); }
And it checks out:
a[3:] -> range(a, 3, undef) -> @a[3 .. 6] 'defg', expecting 'defg' a[0:] -> range(a, 0, undef) -> @a[0 .. 6] 'abcdefg', expecting 'abcdef +g' a[-3:] -> range(a, -3, undef) -> @a[4 .. 6] 'efg', expecting 'efg' a[:3] -> range(a, undef, 3) -> @a[0 .. 2] 'abc', expecting 'abc' a[:0] -> range(a, undef, 0) -> @a[0 .. -1] '', expecting '' a[:-3] -> range(a, undef, -3) -> @a[0 .. 3] 'abcd', expecting 'abcd'

In reply to Re^3: Converting python list range expressions to perl by ibm1620
in thread 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":



  • 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 imbibing at the Monastery: (6)
As of 2024-04-23 08:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found