in reply to How to eliminate duplicated code?

If the file is small, it makes no difference what you do. Don't worry about it. And it does seem like the file must be pretty small, since you are taking field 2 from every line, and concatenating all these fields on your first line of output.

That said, given that the file is so small, it does make sense to read it only once and hold it all in memory for both uses:

my @arr; # no need to initialize (and in any case, "= ''" makes littl +e sense) my @hdr; open( F, "x.txt" ) or die $!; while (<F>) { chomp; my @flds = split /,/; push @array, join( ' ', @flds ); push @hdr, $flds[1]; } print join( '/', @hdr ), "\n"; print join( "\n", @array ), "\n";
(not tested, but should be close, if the OP code is really what you intended)