【问题标题】:Perl statements separated by commas?Perl 语句用逗号分隔?
【发布时间】:2014-08-18 04:00:35
【问题描述】:

在这个修改后的快速排序算法中,我在 Perl 中作为个人项目的一部分进行剖析/重写:

sub quick_sort {
    my @a = @_;
    return @a if @a < 2;
    my $p = splice @a, int( $#a / 2 ), 1;
    (
        quick_sort( grep $_ < $p, @a ),
        $p,
        quick_sort( grep $_ >= $p, @a ),
    );
}

print "Enter a list of numbers, separated by commas (e.g. 2,5,1,7): ";
my @a = split ",", <STDIN>;
@a = quick_sort(@a);
chomp(@a);
print "@a\n";

我很困惑这个语句,或者更确切地说,用逗号分隔的一组语句(我猜?)做什么:

quick_sort(grep $_ < $p, @a),
$p,
quick_sort(grep $_ >= $p, @a);

我什至不知道那叫什么,所以谷歌搜索“用逗号分隔的 perl 语句”之类的东西没有任何用处。我已经尝试用分号分隔它们,但是当我尝试这样做时输出不正确。这叫什么,它在做什么?

【问题讨论】:

    标签: perl quicksort comma


    【解决方案1】:

    最后三行构成一个语句,其结果是一个列表:

    quick_sort(grep $_ < $p, @a), $p, quick_sort(grep $_ >= $p, @a);
    

    该列表是子程序的结果。如果您使用分号,则子例程的结果将是:

    quick_sort(grep $_ >= $p, @a);
    

    这是不正确的。

    【讨论】:

    • 这也是一个很好的答案 - 感谢您的贡献!帮助我学到了一些新东西:)
    【解决方案2】:

    这是对您的子例程的递归调用。这才是它真正的作用:

    sub quick_sort {
    
    ## Grabs the list passed from the main body in to an array a
    my @a = @_;
    
    ## If the scalar value of array is less than 2 
    ## then no sorting is needed so return the array as is
    return @a if @a < 2;
    
    ## If not then grab one element which is from the middle of the array
    my $p = splice (@a, int($#a / 2), 1);
    
    ## Call your method in recursion with list of 3 elements, first being an element smaller
    ## than the sliced, the element obtained from slice and an element
    ## greater than or equal to the sliced one
    quick_sort(grep $_ < $p, @a), $p, quick_sort(grep $_ >= $p, @a);
    

    }

    由于slice 是一个破坏性函数,因此在每次迭代中,您的数组都会缩小到满足以下条件并退出的点。

    return @a if @a < 2;
    

    【讨论】:

    • 谢谢大家的回答,不过这个最详细。谢谢 Jaypal :) 我现在明白了。
    • 逗号分隔的语句支持记录在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多