Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: Manipulating Array Indexes

by tybalt89 (Prior)
on Sep 08, 2020 at 00:31 UTC ( #11121473=note: print w/replies, xml ) Need Help??


in reply to Manipulating Array Indexes

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11121442 use warnings; my @data = qw( 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1 ); my $target = 5; my @answers = map { $data[$_] == $target ? @data[$_ + 1 .. $_ + 3] : ( +) } 0 .. $#data; print "@answers\n";

Outputs:

6 7 8 4 3 2

Replies are listed 'Best First'.
Re^2: Manipulating Array Indexes
by GrandFather (Sage) on Sep 08, 2020 at 01:17 UTC

    Try it with: my @data = qw( 5 );.

    Prints:

    Use of uninitialized value $answers[0] in join or string at 11121473.p +l line 11. Use of uninitialized value $answers[1] in join or string at 11121473.p +l line 11. Use of uninitialized value $answers[2] in join or string at 11121473.p +l line 11.

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

      A) There was no test case for that indicating it is not possible for his data set.
      B) This is one thing I really like about perl - it's easily fixed with just two words and a comma :)

      #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11121442 use warnings; my @data = qw( 5 ); my $target = 5; my @answers = grep defined, map { $data[$_] == $target ? @data[$_ + 1 +.. $_ + 3] : () } 0 .. $#data; print "@answers\n";

        While I agree with B, I think A is rather a stretch. More importantly, good pedagogy suggests showing how to deal with edge cases is an important element of example code. Golf or obfuscation on the other hand tend to be an impediment to teaching concepts. Slices are important enough to be shown free of clutter.

        Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (4)
As of 2020-10-26 18:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (252 votes). Check out past polls.

    Notices?