是否有一个不太笨拙的选择复制到"n"数组元素?

Zai*_*aid 12 perl

在许多的世界@choices
有了$limit什么可以做,
生命注入了许多@options
,但有时只是一个或两个.
为了尽量减少线路噪音Tim Toady
可以做什么?

以下是我想到的一些方法,但它们看起来很笨拙.当然,DWIM有一种更优雅的方式:

mob*_*mob 12

@choices = @options; splice @choices, $limit;  # "splice() offset past end" before v5.16
Run Code Online (Sandbox Code Playgroud)

它也可以在一个声明中完成!

@choices = splice @{[@options]}, 0, $limit;
Run Code Online (Sandbox Code Playgroud)

并且

splice @{$choices_ref=[@options]}, $limit;  # Warns "splice() offset past end" before v5.16
splice $choices_ref=[@options], $limit;     # Ditto. Requires Perl v5.14. "Experimental"
Run Code Online (Sandbox Code Playgroud)


ike*_*ami 7

my @choices = @options[0..min($#options, $limit-1)];
Run Code Online (Sandbox Code Playgroud)

简短,直白,清晰.


Hun*_*len 5

在你提供的选项中,我实际上喜欢#1和#4,并且有明确的书面陈述.如果这些选项真的困扰我,我可能会这样写:

use strict;
use warnings;

use List::Util qw(min);
use Data::Dumper;

my @options = ('a'..'c');
my $limit   = 5;

my @choices = @options[0..min($limit-1, $#options)];
print Dumper \@choices;
# $VAR1 = [
#      'a',
#      'b',
#      'c'
#    ];    

$limit = 2;
@choices = @options[0..min($limit-1, $#options)];
print Dumper \@choices;
# $VAR1 = [
#       'a',
#       'b'
#   ];
Run Code Online (Sandbox Code Playgroud)

但这主要是基于意见的,我相信其他人会以不同的方式做到这一点.