in reply to Adding items to arrays: best approach?
The Perlish way is TIMTOWTDI - both push and @array = (@array, ...) are fine.*
Note that instead of prepending $inputPathPrefix to each value individually, it's probably nicer to use map.
Also, I strongly recommend you don't manipulate filenames with plain string operations, and use modules like Path::Class or the core module File::Spec instead. (Update: I meant to make this same comment on your previous post, but didn't get around to it, sorry)
use warnings; use strict; use Data::Dump; use File::Spec::Functions qw/catfile/; my $inputPathPrefix = "C:/Temp/xml"; my @inputfiles = map { catfile($inputPathPrefix, $_) } 'test1.xml', 'test2.xml', 'test3.xml'; push @inputfiles, map { catfile($inputPathPrefix, $_) } 'test4.xml', 'test5.xml', 'test6.xml', 'test7.xml'; dd @inputfiles; __END__ ( "C:/Temp/xml/test1.xml", "C:/Temp/xml/test2.xml", "C:/Temp/xml/test3.xml", "C:/Temp/xml/test4.xml", "C:/Temp/xml/test5.xml", "C:/Temp/xml/test6.xml", "C:/Temp/xml/test7.xml", )
Update: Clarified first sentence.
Update 2:
What's the habbit in case of initial array declaration and first method: put the comma's at the back or at the front?
Personally, at the back, that's also the most common that I see.
Has the first method advantages over the second method or vice versa? What are the advantages, if any?
* push is faster. But also, IMHO, TIMTOWTDI still applies as long as performance isn't an issue. In other words, if you're only doing this on small arrays once or twice in your code, it's more likely the performance hotspots will be in other places in your code and this amounts to a micro-optimization.
use warnings; use strict; use Benchmark qw/cmpthese/; cmpthese(-2, { push => sub { my @x = (123) x 1000; push @x, (456) x 1000; }, append => sub { my @x = (123) x 1000; @x = (@x, (456) x 1000); }, }); __END__ Rate append push append 23682/s -- -31% push 34524/s 46% --
|
|---|