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

Re^2: Converting python list range expressions to perl

by Marshall (Canon)
on Dec 03, 2022 at 19:28 UTC ( #11148540=note: print w/replies, xml ) Need Help??


in reply to Re: Converting python list range expressions to perl
in thread Converting python list range expressions to perl

you posted first. I did come up with a slight variation on the 2nd task.
use strict; use warnings; use 5.10.0; #for say #a = [ 'a','b','c','d','e','f','g' ] my @a = qw(a b c d e f g); #a[:3] # abc say @a[0..2]; # only first 3 #a[:-3] # abcd say @a[0..$#a-3]; # exclude last 3 #a[3:] # defg say @a[3..$#a]; # exclude first 3 #a[-3:] # efg say @a[-3..-1]; # only last 3

Replies are listed 'Best First'.
Re^3: Converting python list range expressions to perl
by ibm1620 (Friar) on Dec 03, 2022 at 21:35 UTC
    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'

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2023-02-06 06:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (33 votes). Check out past polls.

    Notices?