Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Using s///e and it just doesn't feel right

by kral (Monk)
on Jun 20, 2003 at 15:56 UTC ( [id://267629]=note: print w/replies, xml ) Need Help??


in reply to Using s///e and it just doesn't feel right

like when I see code bastardizing grep or map into doing the work of foreach
I don't understand what you mean when you say "bastardizing".
Functions like grep and map are explicit for working with arrays'elements.
----------
kral
(sorry for my english)

Replies are listed 'Best First'.
Re: Re: Using s///e and it just doesn't feel right
by bunnyman (Hermit) on Jun 20, 2003 at 16:08 UTC

    map should not be used in a void context, that's why foreach is there.

    map { print "$_\n" } (@array);
    foreach (@array) { print "$_\n" }

    These are functionally the same, but map generates a return value that can be assigned to another array, and foreach does not, therefore map is not appropriate. Instead it should be used for its return value:

    @squares = map { $_ * $_ } (@array);

    The above code with foreach would have to be:

    foreach (@array) { push @squares, $_ * $_ }

      When the map function is used as you suggest above, it is being called in void context, which I agree is not as good as for. Having said that, I would suggest that a more perlish idiom of saying the above would not require calling map in void context at all:

      print map "$_\n", @array;

      And better still:

      print join "\n", @array;

      Just some thoughts.

      map should not be used in a void context, that's why foreach is there.

      And why then is map allowed to be called in void context? =)

      -Waswas
        It is addressed in the Perl FAQ.

        There are a lot of things you can do with Perl that you shouldn't do.

      These are functionally the same, but map generates a return value that can be assigned to another array, and foreach does not, therefore map is not appropriate.
      There are also situations where forech aren't appropriate. Like:

      foreach(@array){ push(@tmp, $_) if(/$regex/); }
      But I respect this way of coding 'cause TMOWTDI.
      ----------
      kral
      (sorry for my english)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-19 14:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found