Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Turning foreach into map?

by tlm (Prior)
on Apr 05, 2005 at 00:19 UTC ( #444830=note: print w/replies, xml ) Need Help??

Help for this page

Select Code to Download


  1. or download this
    sub my_map {
      my $sub = shift;
    ...
      }
      return @out;
    }
    
  2. or download this
    sub square { $_[0] * $_[0] }
    my @squares = my_map( \&square, 1..3 );  # @squares is now ( 1, 4, 9 )
    
  3. or download this
    my @squares = my_map( sub { $_[0]*$_[0] }, 1..3 );
    
  4. or download this
    my @squares = my_map sub { $_[0]*$_[0] }, 1..3;
    
  5. or download this
    sub my_map {
      my $sub = shift;
    ...
      }
      return @out;
    }
    
  6. or download this
    my @squares = my_map sub { $_ * $_ }, 1..3;
    
  7. or download this
    my @squares = map { $_ * $_ } 1..3;  # BLOCK form of map
    
  8. or download this
    sub twice { $_ * 2 }
    
  9. or download this
    my @evens = map &twice, 1..10;  # EXPR form of map
    
  10. or download this
    my @evens = my_map \&twice, 1..10;
    
  11. or download this
    sub my_map (\&@_) {
      my $sub = shift;
    ...
      push @out, $sub->() for @_;
      return @out;
    }
    
  12. or download this
    my @evens = my_map &twice, 1..10;
    
  13. or download this
    sub my_map (&@) {
      my $sub = shift;
    ...
      push @out, $sub->() for @_;
      return @out;
    }
    
  14. or download this
    my @evens = my_map { $_ * 2 } 1..3;
    
  15. or download this
    my @evens = my_map $_ * 2, 1..10;        # splat!
    
  16. or download this
    my @ints  = 1..3;
    my @evens = my_map { $_ *= 2 } @ints;
    ...
    __END__
    2 3 6
    2 3 6
    
  17. or download this
    sub my_grep (&@) {
      my $sub = shift;
    ...
      $sub->() && push @out, $_ for @_;
      return @out;
    }
    

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (2)
As of 2023-01-29 03:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?