Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^2: Confusing syntax error with grep

by gumpu (Friar)
on Aug 12, 2004 at 17:25 UTC ( #382386=note: print w/replies, xml ) Need Help??


in reply to Re: Confusing syntax error with grep
in thread Confusing syntax error with grep

"However, it also doesn't make sense because you are using grep in a void context. grep is meant to filter a list (reduce some of the contents out of list1 into list2). If you just want to apply a block of code against every item in a list, think of using map or foreach. Most folks here will complain, likewise, if you use map in a void context"

Guess I agree on using map instead of grep. But I find foreach ugly.

foreach ( @alist ) { if ( condition( $_ ) ) { do_something( $_ ); } }

Is far less pretty to the eye than:

map { condition( $_ ) and do_something( $_ ) } @alist;

OK, map ( or grep ) has to create a list which is not used. I used to worry about that too. However, given the size of an list in an average problem and the amount of memory that is nowadays present in a computer it is no longer relevant to worry about it. For instance in my case the list holds the names of all files in a single directory. That will be 1 to 1000 elements or so. Compared to the 256 Mbyte that is available in my computer this is peanuts. So I stopped worrying about it and instead worry about making it readable.

Of course it would be even nicer if there was a construct in perl like:

{ do_something( $_) } forall ( @alist ) where { condition( $_ ) }

Have Fun

Replies are listed 'Best First'.
Re^3: Confusing syntax error with grep
by ysth (Canon) on Aug 12, 2004 at 18:48 UTC
    Of course it would be even nicer if there was a construct in perl like:    { do_something( $_) } forall ( @alist ) where { condition( $_ ) }
    You mean like: do_something( $_ ) for grep condition( $_ ), @alist; ?

    Update: condition( $_ ) and do_something( $_ ) for @alist; is going to be faster because it doesn't have to loop twice.

      That comes pretty close yes :)

      Have Fun

Re^3: Confusing syntax error with grep
by gumpu (Friar) on Aug 12, 2004 at 18:38 UTC

    Come to think of it:

    foreach ( @alist ) { if ( condition( $_ ) ) { do_something( $_ ); } }

    can be written as

    foreach ( @alist ) { condition( $_ ) and do_something( $_ ) }

    Which is as pretty as the map version. The point about worrying too much about memory still stands though.

    Have Fun

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2022-11-26 22:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?