在许多的世界
@choices
有了$limit什么可以做,
生命注入了许多@options
,但有时只是一个或两个.
为了尽量减少线路噪音Tim Toady
可以做什么?
以下是我想到的一些方法,但它们看起来很笨拙.当然,DWIM有一种更优雅的方式:
详细的单线
my @choices = @options <= $limit ? @options : @options[0..$limit-1]; # Blech
Run Code Online (Sandbox Code Playgroud)切片控制
my @choices = @options[0..(@options <= $limit ? $#options : $limit - 1)]; # Even worse
Run Code Online (Sandbox Code Playgroud)在切片里面的俗气切片
my @choices = @options[0..($#options, $limit-1 )[@options > $limit]]; # Crazy eyes
Run Code Online (Sandbox Code Playgroud)更明确的意图,但超过两行
my @choices = @options;
@choices = @options[0..$limit-1] if $limit < @options;
Run Code Online (Sandbox Code Playgroud)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)
my @choices = @options[0..min($#options, $limit-1)];
Run Code Online (Sandbox Code Playgroud)
简短,直白,清晰.
在你提供的选项中,我实际上喜欢#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)
但这主要是基于意见的,我相信其他人会以不同的方式做到这一点.