in reply to Specifying a range through a variable

my @range = 1..10; for my $x (@range) { print "$x\n"; }

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re^2: Specifying a range through a variable
by Zubinix (Acolyte) on Sep 19, 2008 at 02:26 UTC
    what if the range is passed in as a string? How to do convert the string "1..10" to mean the range 1 through to 10?
      How to do convert the string "1..10" to mean the range 1 through to 10

      A bit kludgey:
      use warnings; my $range = "1..10"; my @wanted = range($range); print "@wanted\n"; sub range { my @t = split /\.\./, $_[0]; return ($t[0] .. $t[1]); }
      Update: To return first and last values, obviously:
      sub range { my @t = split /\.\./, $_[0]; return ($t[0], $t[1]); }
      Cheers,
      Rob
        my @t = $_[0] =~ /^\s*(-?\d+)\s*\.\s*\.(\s*\.)?\s*(-?\d+)\s*$/;
        Be as strict as possible in what you accept. That way, errors are caught as early as possible.

        My criteria for good software:
        1. Does it work?
        2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

      Use eval, if you must.

      my $range = '1..10'; for my $x ( eval $range ) { print "$x\n"; }

      Beware, however, that input validation is very important here. The string you pass into eval can be any Perl code, and it will do whatever that code does.

        Also something like this work to:
        my $a = 1; my $b = 10; my @range = $a .. $b; for my $x (@range) { print "$x\n"; }
        So I could parse the start and end of range into variables. Cool. Thanks.