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

前端 未结 5 1098
名媛妹妹
名媛妹妹 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:05
    my @choices = @options[0..min($#options, $limit-1)];
    

    Short, straightforward, clear.

    0 讨论(0)
  • 2021-01-11 14:05
    my @choices = first_x_ele($limit, @options);
    

    If you think something is unclear, use a sub! How you implement the sub isn't very important, but a short one would be:

    sub first_x_ele { my $x = shift; splice(@_, 0, $x) }
    
    0 讨论(0)
  • 2021-01-11 14:11

    I'd probably use splice:

    my @choices = splice ( @options, 0, $limit ); 
    

    Note that splice acts like shift/pop and modifies the source array - if that's undesirable, then copy it first.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-01-11 14:20

    Of the options you provided I actually like #1 and #4 and have definitely written statements like those before. If those options really bothered me, I might write it this way:

    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'
    #   ];
    

    but this is largely opinion based and I am sure other people would do it differently.

    0 讨论(0)
提交回复
热议问题