Re: better idiom for appending to list from file



On 30 May 2006, wahab@xxxxxxxxxxxxxxxxxxx wrote:

is there a typical Perl-spell when
having a list:

Array = qw( a b c d );

that needs to be appended from a file:

[somefile.txt]
ee
ff
gg
hh
[EOF]

I'd use

splice @Array, @Array, 0, map{ chomp; $_ } <FH>;

for that, but it may look ugly to others.

If your goal is to write nice, portable, maintainable code, you want
to do this:

while (<FH>)
{
chomp;
push @Array, $_;
}

It's longer (4 lines vs. 1), but when you revisit it 3 years later,
you won't spend precious time wondering what it does. You might make
a small argument for efficiency, but I would guess the performance
difference is really small and depends on many other factors. For
large files, in particular, creating the temporary list of all lines
can be deadly for your memory usage, whereas line-by-line processing
will not use much memory at all.

The one-line version would be

push @Array, map { chomp; $_ } <FH>;

but I would hate to see that in code I had to maintain. The
documentation needed and possible confusion are just not worth the
cleverness.

Ted
.