in reply to How to write better code?
In the specific case of the code you've posted, one of the best pieces of advice I'd give is to name things (variables, functions, objects, methods) carefully - and don't be afraid of renaming them if their purpose (or your understanding of their purpose changes).
In this example, people are guessing that you're writing CGI-parsing code, because you've got variables called $string and @array. This doesn't really convey any information to the reader. It would be much better to write something like:
otherwise, what you've written is fairly good, idiomatic perl. If you're interested in some other, nice, more modern idioms, take a look in List::Util and List::MoreUtils. These don't really apply to your code above, but they are a nice way of removing some loops and lines from your code and simultaneously expressing the intent of what you're trying to do more clearly.my $cgi_query_string = "name=alex&sex=m"; my @components = split(/&/, $cgi_query_string); my %query; foreach my $component (@components) { my ($name, $value) = split(/=/, $component); $query{$name} = $value; }
Also, there is a lot (too much?) in the [id://Tutorials] section and also a lot of good advice in the book "Perl Best Practices".
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to write better code?
by derby (Abbot) on Dec 04, 2006 at 15:46 UTC | |
|
Re^2: How to write better code?
by johngg (Canon) on Dec 04, 2006 at 16:58 UTC | |
by jbert (Priest) on Dec 04, 2006 at 17:18 UTC | |
by imp (Priest) on Dec 04, 2006 at 17:20 UTC | |
by johngg (Canon) on Dec 04, 2006 at 20:21 UTC |