子例程中的Perl特殊变量"@_"不起作用

cap*_*ser 0 perl subroutine special-variables

此脚本从下载的网页中删除网址.我在使用这个脚本时遇到了一些麻烦 - 当我使用它"my $csv_html_line = @_ ;" 然后打印出来时"@html_LineArray"- 它只是打印出来"1's".当我更换 "my $csv_html_line = @_ ;"使用"my $csv_html_line = shift ;"脚本工作正常.我不知道有什么不同之处"= @_" and shift- 因为我认为没有具体说明,在子程序中,转移从"@_".

#!/usr/bin/perl
use warnings;
use strict ;

sub find_url {
    my $csv_html_line = @_ ;
    #my $csv_html_line = shift ;
    my @html_LineArray = split("," , $csv_html_line ) ;
    print "@html_LineArray\n" ;
    #foreach my $split_line(@html_LineArray) {
    #    if ($split_line =~ m/"adUrl":"(http:.*)"/) {
    #        my $url = $1;
    #        $url =~ tr/\\//d;
    #        print("$url\n")  ;
    #    }
    #}
}



my $local_file = "@ARGV" ;
open(my $fh, '<', "$local_file") or die "cannot open up the $local_file $!" ;
while( my $html_line = <$fh>) {
    #print "$html_line\n";
    find_url($html_line) ;
}
Run Code Online (Sandbox Code Playgroud)

这就是以上打印出的内容.

1
1
1
1
1
1
1
1
1
1
1
1
Run Code Online (Sandbox Code Playgroud)

这很好 - 它使用移位而不是"@_"

#!/usr/bin/perl
use warnings;
use strict ;

sub find_url {
    #my $csv_html_line = @_ ;
    my $csv_html_line = shift ;
    my @html_LineArray = split("," , $csv_html_line ) ;
    #print "@html_LineArray\n" ;
    foreach my $split_line(@html_LineArray) {
        if ($split_line =~ m/"adUrl":"(http:.*)"/) {
            my $url = $1;
            $url =~ tr/\\//d;
            print("$url\n")  ;
        }
    }
}



my $local_file = "@ARGV" ;
open(my $fh, '<', "$local_file") or die "cannot open up the $local_file $!" ;
while( my $html_line = <$fh>) {
    #print "$html_line\n";
    find_url($html_line) ;
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*son 6

它的

my ($csv_html_line) = @_ ;
Run Code Online (Sandbox Code Playgroud)

您编写@_在标量上下文中评估的代码并获得其长度(元素数)的方式.如你所说,

my $csv_html_line = shift;
Run Code Online (Sandbox Code Playgroud)

因为shift运算符获取列表并删除并将第一个元素作为标量返回,因此可以正常工作.

  • 你没有逗号,你得到空格.为什么要经历连接再次分裂的麻烦?它已经很好地为你分手了.你真的应该在命令行调试器中尝试这样的东西:`perl -de0` (6认同)
  • 你为什么想这么做?你认为完成了什么?如果`@ _`包含多个字符串,引用它将返回连接的所有成员字符串,空白分隔.可能不是你想要的. (4认同)