Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re^3: writtings files to a new folder

by MaxKlokan (Monk)
on Jan 24, 2007 at 12:12 UTC ( #596244=note: print w/replies, xml ) Need Help??

in reply to Re^2: writtings files to a new folder
in thread writtings files to a new folder

Thinking of it, I myself would probably use do {...} foreach @list; as you suggest, because I find it more readable.
At first I found that particular use of grep intriguing. Then again, I wonder whether it was a good idea to add such a (potentially confusing) functionality to grep, since foreach works perfectly fine.

Replies are listed 'Best First'.
Re^4: writtings files to a new folder
by jbert (Priest) on Jan 24, 2007 at 12:22 UTC
    In general, you shouldn't use grep or map for side-effects.

    The purpose of grep is to filter a list into another (possibly shorter) list of elements of the original list. The grep block should really do nothing except evaluate to true or false.

    The purpose of map is to transform a list into another list of the same length1, with the transformation being specified by the return value of the map block.

    The purpose of 'for/foreach' is to loop over a list and perform an action (perhaps with side-effects such as printing) for each element.

    All of these involve looping over the list and, since arbitrary code can be used in the grep or map block, all can be considered as variants on 'for', but with different return values. If you aren't using the return value, you should use for.

    All of the 'should' and 'purpose' above relate to communicating your intent to other coders, of course the code would work whichever construct you used for your loop.

    1OK, because perl flattens lists, you can change the number of list items by having your block evaluate to a list itself, which is useful to construct a hash from a list of keys, for example.

Re^4: writtings files to a new folder
by roboticus (Chancellor) on Jan 24, 2007 at 13:31 UTC

    Any way you can make the code more legible (maintainable) is a good thing. I'm not saying that the grep usage is a bad thing, as I don't know enough Perl idioms to recognize whether it is or not. But the do { ... } foreach @list; is pretty darned easy to read and recognize what the code does.

    Someone (Kernighan?) once said something to the effect of: Debugging is harder than coding. If you write the cleverest code you can, then by definition, you can't debug it.

    If only I could learn to live by that motto ... my life would be a lot simpler.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2020-10-23 00:37 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (234 votes). Check out past polls.