有没有一种不那么笨拙的替代方法来复制“n"?数组元素? [英] Is there a less clumsy alternative for copying up to "n" array elements?

查看:37
本文介绍了有没有一种不那么笨拙的替代方法来复制“n"?数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a world of many @choices
With a $limit to what one can do,
Life proposes many @options
But at times just one or two.
In a bid to minimize line noise
What can Tim Toady do?

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

Here are a few ways I've thought of, but they just seem so clumsy. Surely there's a more elegant way to DWIM:

  • 详细单行

my @choices = @options <= $limit ? @options : @options[0..$limit-1];  # Blech

  • 切片控件

    my @choices = @options[0..(@options <= $limit ? $#options : $limit - 1)]; # Even worse
    

  • 切片里面的俗气切片

    my @choices = @options[0..($#options, $limit-1 )[@options > $limit]];  # Crazy eyes
    

  • 更清晰的意图,但超过两行

    my @choices = @options;
       @choices = @options[0..$limit-1] if $limit < @options;
    

  • 推荐答案

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

    也可以在一条语句中完成!

    It can also be done in a single statement!

    @choices = splice @{[@options]}, 0, $limit;
    

    还有

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

    这篇关于有没有一种不那么笨拙的替代方法来复制“n"?数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆