Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^2: Range Operator in If Statement

by Not_a_Number (Parson)
on Jan 05, 2012 at 16:00 UTC ( #946430=note: print w/ replies, xml ) Need Help??


in reply to Re: Range Operator in If Statement
in thread Range Operator in If Statement

I'm SURE there is a 100 different ways to do this...

Here's one way to assign to $bundle that requires a lot less typing. Replace your call to get_bundle and the sub itself with:

$bundle = [ 'A' .. 'F' ]->[ ( $ref_number - 1 ) / 8 ];

Update: Removed unnecessary parentheses around the arrayref.


Comment on Re^2: Range Operator in If Statement
Select or Download Code
Re^3: Range Operator in If Statement
by mmartin (Monk) on Jan 05, 2012 at 19:23 UTC
    Not_a_Number, thanks for the reply...

    Cool stuff... Could you explain a little how that works exactly? I'm still relatively new to Perl.


    Thanks,
    Matt


      Could you explain...

      Let me try. First,

      [ 'A' .. 'F' ]

      is a reference to an anonymous arrray (see references quick reference). To access, for example, the second element of this array, the syntax is:

      [ 'A' .. 'F' ]->[1]

      (You could also do ${ [ 'A' .. 'F' ] }[1] but I find the first form cleaner.)

      Then, instead of hard-coding the array index, my snippet calculates it in the fashion indicated in LanX's post above. The only difference is that I've removed int() since perl happily does this part of the job for me when I use a floating point number as an array index.

      To clarify, the following code, using a named array and an intermediate variable ($index), does the same thing:

      my @array = ( 'A' .. 'F' ); my $ref_number = 42; # or whatever my $index = ( $ref_number - 1 ) / 8; my $bundle = $array[ $index ]; print $bundle;

      hth, dave

        Hey thanks for the explaination...

        I'll give it a try and see how it goes.

        Thanks Again,
        Matt

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2014-09-23 22:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (241 votes), past polls