Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Test if list is range

by DeepThought (Initiate)
on Sep 29, 2012 at 11:17 UTC ( #996362=perlquestion: print w/replies, xml ) Need Help??
DeepThought has asked for the wisdom of the Perl Monks concerning the following question:

Can I test if a variable is either a [1, 2, 3 ] list or a [1 .. 3 ] range?


Replies are listed 'Best First'.
Re: Test if list is range
by LanX (Chancellor) on Sep 29, 2012 at 11:33 UTC
    please use <code> tags!

    No, there is (unfortunately) no range datatype, the range operator does only create a list in list context.

    If you need ranges as types , consider creating an object or tie handling the behavior you want.

    You could also try one of the cpan modules for ranges.

    Cheers Rolf

      There might be a way

      $ perl -MO=Deparse -e " use Data::Dump; dd [ 1,2,3 ] " use Data::Dump; dd([1, 2, 3]); -e syntax OK $ perl -MO=Deparse -e " use Data::Dump; dd [ 1..3 ] " use Data::Dump; dd([1..3]); -e syntax OK
        for this you need to know where in the source an array variable was set ....

        Its like trying to determine if ones grandparents where married by screening his bloodsample.

        Cheers Rolf

Re: Test if list is range
by Kenosis (Priest) on Sep 29, 2012 at 15:05 UTC

    Perhaps Perl's (v5.10+) smart-match operator can help:

    use strict; use warnings; my @array = qw/1 2 3/; print 'The variable is ' . ( is123(@array) ? '' : 'not ' ) . '[1 .. 3] +.'; sub is123 { @_ ~~ [ 1 .. 3 ] }


    The variable is [1 .. 3].

      Hm, I guess I could use the first and last element of a array and create a range with that which I can compare against the array like this to see if it is identical.

      But I think I will just ignore the problem and expect the user to tell me what he wants. The range operator would have been very nice meta programming syntax sugar though.

      I wanted to use it for data validations where for a test a user could pass a list or range of valid entries. But of course for a range I don't want to actually test every element just a few within the range.

      Thanks for all your answers

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://996362]
Approved by LanX
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2017-02-22 00:14 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (322 votes). Check out past polls.