Pathologically Eclectic Rubbish Lister PerlMonks

### Use an array slices

by nite_man (Deacon)
 on Feb 28, 2003 at 08:57 UTC Need Help??
 Description: I needed a showing of choices in the drop down list according to some criterion (object status, in my case). So, I used an array slices instead use loop.I hope that this decision will be usefull somebody. ;)
```
my @list = ( [0, 'Zero'], [1, 'One'], [2, 'Two'], [3, 'Three'],
[4, 'Four'], [5, 'Five'], [6, 'Six'] );

SWITCH: for (\$some_obj->get_status) {
/0/ && do { @list = @list[0, 6]; last; };
/1/ && do { @list = @list[0..2]; last; };
/2/ && do { @list = @list[2..5]; last; };
/3/ && do { @list = @list[3];    last; };
/4/ && do { @list = @list[4];    last; };
/5/ && do { @list = @list[2, 5]; last; };
/6/ && do { @list = @list[6];    last; };
@list = ();
}

\$"=', ';

print "Result: status = ".\$some_obj->get_status."; list=@list";

```
Replies are listed 'Best First'.
Re: Use an array slices
by Hofmator (Curate) on Feb 28, 2003 at 09:30 UTC
An alternative to the 'switch' is using a dispatch array. I'm assuming for the following that \$some_obj->get_status returns an integer number, otherwise this number has to be extracted from the return value:
```# choice number  0       1       2     3    4     5     6
my @choices = ([0,6], [0..2], [2..5], [3], [4], [2,5], [6]);

my \$num = \$some_obj->get_status;
my @newlist = @list[ @{ \$choices[\$num] } ];

local \$"=', ';

print "Result: status = \$num; list=@newlist";

-- Hofmator

Re: Use an array slices
by blakem (Monsignor) on Feb 28, 2003 at 09:31 UTC
Have you thought about what happens when you add the tenth (i.e. '10') branch?

-Blake

This decision doesn't have pretensions on absolutly universality. I have just had a case with fixed choises. If I will add the tenth branch, I will add a choice for it.
```#!/usr/bin/perl -w

use strict;
I assume that case would look something like this:
```#!/usr/bin/perl -wT
use strict;

my \$value = 10;

SWITCH: for (\$value) {
/0/  && do {print "ZERO\n"; last; };
/1/  && do {print "ONE\n";  last; };
/10/ && do {print "TEN\n";  last; };
print "NONE OF THE ABOVE\n";
}
Can you guess what the output is? Run it and find out.

-Blake

Create A New User
Node Status?
node history
Node Type: snippet [id://239372]
help
Chatterbox?
and a soft breeze sighs...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2018-05-25 01:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
World peace can best be achieved by:

Results (181 votes). Check out past polls.

Notices?