in reply to question about variables from new perl user
G'day rst,
Welcome to the Monastery.
"Note, this question is about the particular code snippet, ..."
The responses you've received so far, appear to have covered most aspects of this.
I would just add, that when you find yourself coding lists of sequentially numbered variables, take a step back and reconsider your approach. You probably don't need to write that much code but, more importantly, what you're writing is very error-prone.
Even with the few lines you have here, it's completely unclear what any of the $tN variables actually refer to. While it may be fairly easy, from the context of initialisation, to determine what, say, $t3 holds; finding $t3 by itself, a screen or two later, won't be at all helpful: you'll probably need to scroll back to the initialisation code to determine what data it holds.
It's also far too easy, with a typical typo caused by accidentally hitting a key adjacent to the one you want, to type $t2 or $t4 instead of $t3. When eyeballing the code, this won't immediately leap out at you as a mistake and, given they're all valid variables, Perl probably won't be in a position to alert you to the problem. It's quite likely that you'll end up with a bug that's hard to track down.
There's an even more subtle problem here. Array indices in Perl are zero-based while your sequential numbering starts at one. So, it's not intuitively obvious whether $t3 was the 3rd or 4th value returned: back to scrolling again.
GrandFather has shown improvements with both meaningfully named variables and hash keys. Here's another way with meaningfully named array indices.
use constant { CONTENT_TYPE => 0, DOCUMENT_LENGTH => 1, ... }; ... my @head_values = head(...); ... # later in the code far from the initialisation ... $head_values[DOCUMENT_LENGTH] ...
You now have $head_values[DOCUMENT_LENGTH] which is fairly clear and obvious. Furthermore, even not-so-obvious typos (e.g. $head_values[DOCUMENT_LEMGTH]) will be picked up by Perl at compile time, assuming you've used the strict pragma (which you should always use).
"... but even more it is about understanding variables in Perl."
I suggest you start by reading "perlintro -- a brief introduction and overview of Perl". This manpage isn't long and, given "I'm new to perl, but not programing", should not present you with any difficulties. While I recommend you read it in its entirety, the "Perl variable types" and "Variable scoping" sections most closely answer what you're asking today.
The great thing about this piece of documentation is that it's peppered with numerous links to more detailed information and advanced topics. Get the foundation knowledge first then follow the links for greater enlightenment.
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: question about variables from new perl user
by rst (Initiate) on Dec 01, 2015 at 03:21 UTC | |
by Athanasius (Archbishop) on Dec 01, 2015 at 03:45 UTC |