[VPM] Perl coding styles (was Re: regex found matches array)
Darren Duncan
darren at darrenduncan.net
Sun Mar 1 20:06:56 PST 2009
peter at psdt.com wrote:
> Darren wrote:
>> Say something like this:
>>
>> my $results = [$source =~ m/$pattern/g];
>>
>> Then the $results array has one element per capture by the pattern.
>
> s/array/arrayref/.
>
> Any reason not to skip the enreferencing?
>
> my @results = ( $source =~ m/$pattern/g );
Well yes, that version also works, by the same principles.
The reason I used an arrayref in the example is because that is an aspect of my
preferred Perl coding style.
I find that using arrayrefs and hashrefs rather than arrays and hashes leads to
more consistency in code. First this is since in the general case you have to
use the refs version often, either if you want routines to accept or return
collections without them flattening or if you want to have collections as
elements of other collections or as object attributes; all of these happen very
frequently in my experience, so why not just use the refs all the time and be
done with it; it means I don't have to mix and match syntaxes. In addition,
using just refs lets me name all my variables with $, which is another kind of
consistency that makes my code a lot easier to read and understand, and once
again is more consistent (and it also helps counter the argument by users of
other languages about all the different Perl sigils being confusing; you don't
have to use them); no @ or % is needed except for whole-collection derefs or
when using @_. And not flattening by default is more DWIM and makes the code
easier to understand. Also, on the list construction side, using [] and {}
clearly documents we are building an ordered or an unordered list, whereas () on
the right hand side does not; so easier to understand yet again.
So, I see lots of advantages of my preferred style, and no drawbacks.
And besides which, using the refs also makes the Perl 5 semantics more like the
default Perl 6 semantics, which is to not flatten collections by default.
-- Darren Duncan
More information about the Victoria-pm
mailing list