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

$regex = join('|', map{"\\.$_" }@edittypes); What is the map function doing in this

Replies are listed 'Best First'.
Re: Ahh the map function
by DamnDirtyApe (Curate) on Jul 07, 2002 at 04:12 UTC
    map BLOCK LIST map EXPR,LIST Evaluates the BLOCK or EXPR for each element of LIST (locally setting "$_" to each element) and returns the list value composed of the results of each such evaluation. In scalar context, returns the total number of elements so generated. Evalu­ ates BLOCK or EXPR in list context, so each ele­ ment of LIST may produce zero, one, or more ele­ ments in the returned value. @chars = map(chr, @nums); translates a list of numbers to the corresponding characters. And %hash = map { getkey($_) => $_ } @array; is just a funny way to write %hash = (); foreach $_ (@array) { $hash{getkey($_)} = $_; }

    So, for each element in @edittypes (let's say $_ = 'foo'), it would spit out \.foo. The return value from map would be a list of these transformed elements.

    Update: Corrected escaping of backslash.


    _______________
    D a m n D i r t y A p e
    Home Node | Email
      $regex = join('|', map{"\\.$_" }@edittypes); inerror("You can only edit \"@edittypes\"") unless /$regex/i;
      Im confused with whole thing can oyu explain in words how it does it.

        OK, Let's say @edittypes = ( 'foo', 'bar', 'zoot' ). For each of these, map sets $_ to the array element, and spits out the return value of the block. So, map returns ( '\.foo', '\.bar', '\.zoot' ). These are joined with pipes; after executing the first line, you have $regex = '\.foo|\.bar|\.zoot'.

        Now, since you don't appear to be matching to anything in the second line, I am guessing this came from inside a loop with an implicit value. Whatever $_ is equal to when the second line runs is matched against $regex, case insensitive. If there's no match, call the inerror function, whatever that may be.

        Does that clear it up?

        Update: Corrected escaping of backslash.


        _______________
        D a m n D i r t y A p e
        Home Node | Email
        A reply falls below the community's threshold of quality. You may see it by logging in.
        A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Ahh the map function
by Juerd (Abbot) on Jul 07, 2002 at 10:16 UTC