|Think about Loose Coupling|
Re: elsif statement not being evaluatedby eyepopslikeamosquito (Chancellor)
|on Nov 18, 2012 at 11:09 UTC||Need Help??|
Since I assume you are new to Perl and to programming, permit me to give you some general advice:
Your code could be written more simply like this:
First notice that I replaced:
which is easier to read and maintain. This uses a feature of Perl called "here-documents". See perlop (search for << in the "Quote-Like Operators" section).
I added the lines:
The chomp is to remove the newline before checking whether $choice is equal to 'q' or not. Note that I used the "alphabetic" operator eq rather than the numeric equivalent ==. In Perl, the "alphabetic" version of an operator (in this case eq) compares the two operands as if they are strings, while the "punctuation" version (in this case ==) compares them numerically. For example, "01" eq "1" is false because the strings are of different length, while "01" == "1" is true because, numerically, they both evaluate to one. See perlop ("Equality Operators" section) for more information.
I set the default value via:
Note the "my" variable declaration, which is required by "use strict". Variables declared with "my", known as "lexical variables", are known from the point of declaration to end of scope. This protects you from many common booboos, such as mis-spelling a variable name, and generally makes the code easier to understand and maintain by explicitly limiting variable scope. See strict for details.
Finally, I reorganized the code to remove unnecessary code duplication (see DRY). That is, the "user entered" data just sets the @lines array. Nothing more. That guarantees that the identical code is used for both the default case and the user-entered case. Your original code had slightly different code for the two cases. Also, your code was needlessly altering the array. For example, instead of your:
which needlessly changes the @proglines array, you can simply print the formatted lines without changing the @proglines array like so:
if you want to get fancy.
Update: as for why you should use strict, I found these nodes: