in reply to To splice or not to splice? What implementation is more readable, efficient, etc.?

Hi vr,

Perl's "no-no" -- the C-style loop

I have to strongly disagree that the C-style loop is a "no-no". The reason the foreach loop is so often recommended over the C-style loop is that many people, especially those coming from other languages, use the C-style for when Perl's foreach would have been more appropriate. But that doesn't mean there's anything wrong with the C-style for. In fact, of all of the code samples you showed, that sub is the only one I understood on the first reading!

As for the other example subs, remember that attempting to be "clever" and golf code is usually a direct hindrance to later maintenance. I know it doesn't feel very perlish to be a little more verbose and, for example, use a for instead of map or to use if/else instead of ? :, but a long map block or ? : structure are less readable and therefore harder to understand and maintain. That doesn't mean they should always be avoided, but require developing a feeling for what will be more readable later.

I know you said you're asking about style, but perhaps you could give some background on the problem anyway. If this data structure is something you're getting from somewhere else and you can't change it (e.g. JSON), then I understand that jumping through some hoops to walk it may be necessary. In that case, maybe you could show some sample input with the expected output.

On the other hand, if this data structure is something you're building yourself, then perhaps you could consider an OO approach as one option. Hiding this data in objects, perhaps even ones that can serialize and deserialize themselves to your data structure, may help greatly in making the code cleaner.

Hope this helps,
-- Hauke D

  • Comment on Re: To splice or not to splice? What implementation is more readable, efficient, etc.?
  • Select or Download Code