gpt4 book ai didi

perl - 如何将文件名传递给 perl 中的子程序?

转载 作者:行者123 更新时间:2023-12-01 07:54:52 26 4
gpt4 key购买 nike

我正在编写一个 perl 脚本,我想将输出文件的文件名传递给子例程。

我试过这样的事情:

use strict;
use warnings;

test("Output.dat");

sub test {
my $name = @_;

open(B, ">$name") or die "Failure \n";

print B "This is a test! \n";
close(B);
}

我将多次使用子例程,所以我必须传递文件名并且不能在子例程中声明它。

我希望你能帮帮我 :)

最佳答案

你的问题是这一行:

my $name = @_;

您正在将数组分配给标量变量。在 Perl 中,这将为您提供数组中元素的数量 - 所以我希望您在 $name 中得到“1”。

有多种方法可以从数组中获取第一个元素;
my $name = $_[0]; # Explicitly get the first element
my $name = shift @_; # Get the first element (and remove it from the array)
my $name = shift; # Same as the previous example - shift works on @_ by default in a subroutine
my ($name) = @_; # The parentheses make it into a list assignment

最后两个是您最常看到的。

还有几点:

1/如果您在错误消息中包含 $name,您将获得更好的问题线索。
open(A, ">$name") or die "Failure: $name \n";

或者,更好的是 Perl 从您的操作系统获得的错误消息。
open(A, ">$name") or die "Could not open $name: $!\n";

(我已经重新添加了缺少的逗号 - 我认为这是一个错字。)

2/如今,使用 open 和词法文件句柄的三参数版本被普遍认为是一种好习惯。
open(my $output_fh, '>', $name) or die "Failure: $name \n";

3/在您的示例中,您打开一个名为“A”的文件句柄,然后尝试写入名为“B”的文件句柄。这是笔误吗?

关于perl - 如何将文件名传递给 perl 中的子程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31311306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com