Is there a less clumsy alternative for copying up to “n” array elements?

前端 未结 5 1142
名媛妹妹
名媛妹妹 2021-01-11 13:57

In a world of many @choices
With a $limit to what one can do,
Life proposes many @options
But at time

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-11 14:15

    @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;
    

    And also

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

提交回复
热议问题