http://www.perlmonks.org?node_id=311421


in reply to Using expressions in arrays for pattern matching

I think the major issues are discussed. So I'll just add one important thing that could save you a lot of time in the future. Since you say you are a new programmer - you're lucky to get to know about this early and pick up good habits.

What I'm talking about is coding readably. It might sound unimportant, but believe me, when your programs will start getting longer, even you won't be able to quickly remmember what you wanted to do in lines 20-35 after working for a while on line 315-377 - not to mention different files. If you'll work in a team you'll even cause more casualties.

The first and foremost is to give meaningful names to variables. $i is customarily a loop counter, but if your loop gets longer, nobody will be able to tell that $i holds the file name without some serious reading, sometimes not even you. You don't have to use Java-like names like $fileNameVariableIUseTemporarily :) but it's a lot better to write:

foreach my $param (@params) { ... } foreach my $file (@files) { ... }

instead of

foreach $x (@params) { ... } foreach $i (@files) { ... }

Secondly - indentation. Ok, I can follow your small script here, but what if I get a code with 3-4 nesting levels over 40-50 lines? You'll soon start banging your head against the wall if your indentation will fail you...

Even worse, you sometimes get a block of closing braces - like the last four lines of your script. In really big blocks I comment them so I'll know what ends what (just like good old BASIC where putting the counter name at the end of a FOR loop was standard syntax).

Phew... pretty long. But you'll thank me later :) I had more than my fair share of unreadable code and I'm trying to save you the bother.

And now for something completely different: why

$x=$&; print OUTPUT "$x\n";
when you can print OUTPUT "$&\n"; ?

That's it. Have fun learning programming!