开发者

Easy way to execute a statement many times in Perl

开发者 https://www.devze.com 2023-02-19 09:14 出处:网络
Is there a shorthand way by which I can push n identical elements to an array ? Can开发者_运维百科 I do this in just one line ?

Is there a shorthand way by which I can push n identical elements to an array ?

Can开发者_运维百科 I do this in just one line ?

push(@mode_z00,"lib_drx");
push(@mode_z00,"lib_drx");
push(@mode_z00,"lib_drx");
push(@mode_z00,"lib_drx");
push(@mode_z00,"lib_drx");

something like push(@mode_z00,5,"lib_drx");


Use the x operator to make multiple copies of a value.

push(@array, ('foo') x 5);


Please do not do this:

map( $list[$_] = "lib_drx", (0..4) );

thats called using map in void context.


push(@mode_z00,'lib_drx') for 1..5;


I'm going to post a different approach that's a bit more flexible with indexing (you could use this to populate a list at a specific range of indices, for example):

#!/usr/bin/perl                                                                                                                                            

use strict;
use warnings;
use Data::Dumper;

my @list;
map($list[$_] = "lib_drx", (0..4));
print Dumper \@list;

When run:

$ ./mapTest.pl
$VAR1 = [
          'lib_drx',
          'lib_drx',
          'lib_drx',
          'lib_drx',
          'lib_drx'
        ];

The use of push() seems faster for very large populations, but map() lets you specify arbitrary start and stop indices:

#!/usr/bin/perl                                                                                                                                            

use strict;
use warnings;
use Benchmark;

my $startTime = new Benchmark();

my $startIndex = 0;
my $stopIndex = (1000000 - 1);
my @list;
map($list[$_] = "lib_drx", ($startIndex..$stopIndex));

my $stopTime = new Benchmark();

print STDOUT "runtime: ".timestr(timediff($stopTime, $startTime), 'all')." sec\n";

For a million additions, here is the runtime of the map() approach:

runtime:  1 wallclock secs ( 0.36 usr  0.10 sys +  0.00 cusr  0.00 csys =  0.46 CPU) sec

And for the push() approach:

#!/usr/bin/perl                                                                                                                                            

use strict;
use warnings;
use Benchmark;

my $startTime = new Benchmark();

my $count = 1000000;
my @list;
push(@list, ('lib_drx') x $count);

my $stopTime = new Benchmark();

print STDOUT "runtime: ".timestr(timediff($stopTime, $startTime), 'all')." sec\n";

The runtime for push() is a little less than half that of the map() runtime:

runtime:  1 wallclock secs ( 0.18 usr  0.07 sys +  0.00 cusr  0.00 csys =  0.25 CPU) sec
0

精彩评论

暂无评论...
验证码 换一张
取 消