【问题标题】:Perl special variable "@_" in a subroutine not working子例程中的 Perl 特殊变量“@_”不起作用
【发布时间】:2016-02-22 11:38:48
【问题描述】:

此脚本会从下载的网页中提取网址。我在使用这个脚本时遇到了一些问题 - 当我使用 "my $csv_html_line = @_ ;" 时 然后打印出"@html_LineArray" - 它只是打印出"1's"。当我更换 "my $csv_html_line = @_ ;""my $csv_html_line = shift ;" 脚本工作正常。 我不知道"= @_" and shift 之间有什么区别 - 因为我认为 不指定任何内容,在子例程中,从"@_".shift 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) ;
}

这是上面打印出来的内容。

1
1
1
1
1
1
1
1
1
1
1
1

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

#!/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) ;
}

【问题讨论】:

标签: perl subroutine special-variables


【解决方案1】:

这是

my ($csv_html_line) = @_ ;

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

my $csv_html_line = shift;

之所以有效,是因为shift 运算符采用一个列表并删除第一个元素并将其作为标量返回。

【讨论】:

  • 如果我在特殊变量周围加上双引号 - my $csv_html_line = "@_ " ;
  • 您为什么要这样做?你认为这能实现什么?如果@_ 包含多个字符串,引用它将返回所有连接的成员字符串,以空格分隔。可能不是你想要的。
  • 引用特殊变量会将整个数组打印到标量,然后标量可以用逗号分割,然后放在另一个数组中。
  • 你没有逗号,你有空格。为什么要经历连接然后再次分裂的麻烦?它已经为你很好地分开了。你真的应该在命令行调试器中尝试这样的东西:perl -de0
【解决方案2】:

你需要

my ($csv_html_line) = @_ ;

将数组分配给标量将返回其长度(带一个参数为 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多