Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Use an array slices

by nite_man (Deacon)
on Feb 28, 2003 at 08:57 UTC ( [id://239372]=CUFP: print w/replies, xml ) Need Help??

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-24 20:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found