1) Like ikegami, I spend a fair bit of time on SO answering Perl questions and one of my common pieces of advice is "don't use C-style for
loops in Perl; use the list iterating version instead because it's harder to mess it up". If you write for my $i (1 .. 10)
, there's no way you're going to get the boundary conditions wrong, plus it's quicker to write and requires less thought than the C-style equivalent. If I were an interviewer and saw you write for (my $i = 1; $i <= 10; $i++)
instead, I would question how well you know Perl and whether you were writing Perl directly or if you were thinking in C, then translating it to Perl.
If I saw you write for (my $i = 1; $i <= 10; $i++) { $data = $some_array[$i];... }
instead of for my $data (@some_array) { ... }
, on the other hand, then I would conclude that you clearly don't know Perl very well and the interview would be pretty well over in my mind, assuming it was for an experienced Perl position. (Unless $i
was going to be used for something else beyond just sequentially indexing into @some_array
, but even then I'd favor for (..)
over for (;;)
.)
Style does matter, especially with a language that's as TIMTOWTDI as Perl. There are many ways to do it, but not all are equally good (for any given value of "good", which does vary from situation to situation). Using all the language features isn't necessary for good style, but using the right ones when they're appropriate will get you pretty far in that direction.
2) Regarding the linked answer, your code there looks fine to me overall. The main thing I question is the &
prefix on your final function call. You don't need it (unless you're writing Perl 4, in which case you have far bigger problems!) and it's generally discouraged these days because it has side-effects which aren't immediately obvious. Definite bonus points for using strict
, three-arg open
, lexical filehandles, and CPAN modules, though.
On the larger point of your second question, I frequently rewrite people's code to clean it up and show (at least some elements of; I try to match it to their apparent skill level) how I would do it. It's not meant as a slight on the original author; it's an attempt to help and to educate beyond the immediate question at hand. It's usually pretty fun, too. But, perhaps most importantly, the simple fact of the matter is that Perl has an image problem. There are a lot of people out there (*cough*Job*cough*) who think that "there is no such thing as good Perl style" and I feel that it's important to disprove that belief by showing off well-written, maintainable Perl code when the opportunity presents itself.