【问题标题】:function call in perlperl中的函数调用
【发布时间】:2014-07-15 23:26:22
【问题描述】:

作为我课程的一部分,我在过去几周第一次学习了 perl 编程语言。我一直在编写小函数并进行函数调用。我写了一个字符串匹配函数。

use strict;
use warnings;

sub find_multi_string {
    my ($file, @strings) = @_; 
    my $fh;
    open ($fh, "<$file");
    #store the whole file in an array
    my @array = <$fh>;

    for my $string (@strings) {
        if (grep /$string/, @array) {
            next;
        } else {
            die "Cannot find $string in $file";
        }   
    }   

    return 1;
}

find_multi_string('file name', 'string1','string2','string3','string4','string 5');

在上面的脚本中,我在函数调用中传递参数。该脚本有效。 但我想知道是否有办法在程序本身的数组中指定文件名和string1...string n,然后调用函数。

find_multi_string();

【问题讨论】:

  • 为什么?你想达到什么目的?
  • 使用autodie!

标签: perl function subroutine


【解决方案1】:

那将是一个错误,始终将参数和返回值传递给您的子例程。

您所描述的本质上是仅使用子例程来细分和记录您的代码。如果您要这样做,最好完全删除子例程并在代码部分之前添加注释。

总体而言,您的代码看起来不错。不过,您可能会想使用quotemeta,并且您的逻辑可以简化一点:

use strict;
use warnings;
use autodie;

sub find_multi_string {
    my ($file, @strings) = @_; 

    # Load the file
    my $data = do {
        open my $fh, "<", $file;
        local $/;
        <$fh>
    };

    for my $string (@strings) {
        if ($data !~ /\Q$string/) {
            die "Cannot find $string in $file";
        }   
    }   

    return 1;
}

find_multi_string('file name', 'string1','string2','string3','string4','string 5');

【讨论】:

  • 用 \Q 将裸字符串转换为正则表达式是一种资源浪费。只需使用index 函数,因为这样会更有效率。
【解决方案2】:

对原始代码的一些改进:

  • 使用autodie
  • 使用 3-args open
  • 如果您想检查文件中的任何位置,只需将文件加载为单个字符串
  • 如果匹配的字符串只是没有来自正则表达式的元字符的文本,只需使用index函数

您的问题是关于从程序中传递函数参数。 我怀疑您正在寻找@ARGV。见perlvar

这里是修改后的代码:

use strict;
use warnings;
use autodie;

sub find_multi_string {
    my ($file, @strings) = @_; 

    my $content = do {
        open my $fh, '<', $file;
        local $/;
        <$fh>
    };


    foreach (@strings) {
        die "Cannot find $string in $file" unless index($content, $_) >= 0;
    }   

    return 1;
}

find_multi_string(@ARGV);

【讨论】:

    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2011-05-28
    • 1970-01-01
    • 2011-07-12
    • 2015-08-17
    • 2012-11-13
    相关资源
    最近更新 更多