Matija Papec wrote at Thu, 17 Jul 2003 22:27:08 +0200:
I was wandering what would be more readable for code maintainers, I prefer
first as it's far more obvious what's going on(not to mention typing
laziness), but that's just me.
#1
@arr = join ',', map s|'|\\'|g && "'$_'", grep /^MB/, @arr;
^^^^ ^^^^
An array
result is a string!
#2
@arr = join(',', map(s|'|\\'|g && "'$_'", grep(/^MB/, @arr)));
I wouldn't look so much to the brackets regarding for code maintainers.
It is easy and simple to understand that both lines
do a comma-join over all transformed elements of @arr that starts with MB.
What is hard to understand on the first view is the transformation that
has to be done. You first need to think some seconds only to comprehend it. And
even if you did it, you can't be sure whether the implemented algorithm
was also the intended one. That is dangerous for maintainance.
I think it would be better to write a subroutine doing exactly this
transformation. If the subroutine has a sensful name, the maintainer can
read and understand without any thinking what the line does. In addition,
he/she can decide whether the transformation does what the subroutine name
says or a completely different transformation will be needed instead.
Let's say something like:
sub escape_single_quotes($) {
my $string = shift;
$string =~ s,',\\',g
and return qq/'$string'/
or return $string;
}
my $str = join ",", map escape_single_quotes($_), grep /^MB/, @arr;
Note, that I also did two other slight changes.
First I changed the pipe symbol to a comma in the substitution.
Not that the comma is so much better, but IMHO the pipe is that worse,
as it is also the alternation operator with such a special meaning in
substitutions, that it is very confusing (and thus less readable) if it
is used as delimiters in regexps.
Second I wrote "'$string'" as qq/'$string'/. I wanted to emphasize that
the returned value is in principle the '$string' in contrast to the simple
$string. I prefer not to have "' or '" in a text as single and double
quotes look similar and are hard to distinguish if they are very near in
the next. (But that's perhaps more a personal style than a hard
maintainance demand)
and another one, how do you prefer $h{key} over $h{'key'} in case where key
is strictly English \w class?
Both doesn't matter for readability and maintainance. I, personally, wouldn't write
$h{'key'} where it isn't necessary (main reason is laziness),
but both ways are easy to read, understand and change.
Most importantly, what would you tell to someone who doesn't have a clue
about use strict and warnings, and at the same time insisting on quoted hash
keys?
Who has no clue about strict and warnings, should not maintain my code!
Greetings,
Janek