Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,
I have recently embarked on my journey in Perl and I am already stuck with my first (most likely super trivial problem: I found a code snippet that I want to practice changing, where the example has the following array:
@ranges = ([172,178],[183,189],[201,208]);

and the command:
$input =~ s/(\d+)/(grep {$1 >= $_->[0] && $1 <= $_->[1]} @ranges) ? $s +ymbol : $1/eg;

So, my problem is, how can I create the @ranges array in the way it's written in this example? I've been trying several ways, like:
@ranges = (); push @ranges, "[172,178]"; push @ranges, "[183,189]"; push @ranges, "[201,208]";

but the code does not run (it runs properly using the above snippet, but somehow the array must be written in the form I have specified above, else the grep command does not work. Can you help me please?

Replies are listed 'Best First'.
Re: Super newbie array question
by 1nickt (Canon) on May 22, 2023 at 22:02 UTC

    Just push the anonymous arrays onto your array without quoting them. Otherwise you have an array of strings.

    my @ranges = (); push @ranges, [172,178]; push @ranges, [183,189]; push @ranges, [201,208];
    Note that if you used strict (you should always use strict), Perl would have told you what the problem was: Can't use string ("[172,178]") as an ARRAY ref while "strict refs" in use.

    Hope this helps!


    update: clarified terminology

    The way forward always starts with a minimal test.
      Aha! I see, that did the trick! And, if I may ask one more thing: if I have $var1 = 172 and $var2=178 instead of the raw numbers themselves, how can I do the push then?
        Interesting, it seemed to work:
        push @ranges, [$var1,$var2];
Re: Super newbie array question
by kcott (Archbishop) on May 23, 2023 at 00:12 UTC

    You'll probably find "perlintro - a brief introduction and overview of Perl" to be generally useful. Note that each section has only basic information but is peppered with links to more in-depth discussions and related documentation. I'd suggest bookmarking this page and returning often when you need specific information.

    For the area that you're currently investigating, I'd recommend "perllol - Manipulating Arrays of Arrays in Perl".

    When you take the next step into other, and more complex, data structures: "perldsc - Perl Data Structures Cookbook".

    I'd also recommend bookmarking "Perldoc Browser". This has links to all of the Perl core documentation.

    Later, when you start looking at modules beyond the core offering, you'll find meta::cpan to be invaluable.

    Consider registering a username so that we can tell your posts from the tens of thousands (101,210 at the time of writing) of other anonymous posts. It's very easy: see "Create A New User".

    — Ken