Perl 将变量传递给子程序 [英] Perl Passing Variable to subroutines

查看:41
本文介绍了Perl 将变量传递给子程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对现有 Perl 脚本进行更改.我正在尝试添加一个在不同位置多次调用的子程序,并根据调用位置打印不同的输出.

I am trying to make changes to an existing Perl script. I am trying to add a subroutine that is called many times at different places and prints different output based on where is it called.

基本上,它会创建一个文件并为业务团队编写一些业务消息(我是其中的一员,因此我第一次使用 Perl 进行编码).

Basically, it creates a file and writes some business message for the business team (I am part of and hence my first time coding in Perl).

我想要/正在尝试的是

Sub filemessage ($arg1) {
  open(fh, '>', $message_file);
  print fh "$arg1/n";
  close fh;
}

现在我想在很多地方(在其他子例程内)像这样调用这个子例程(已经有一个失败条件基于它被调用):

Now I want to call this subroutine at many places (inside other subroutines) like this (there is already a fail condition based on which it is called):

filemessage ("failed due to reason1")
filemessage ("failed due to reason2")

推荐答案

Sub filemessage ($arg1) {
  open(fh, '>', $message_file);
  print fh "$arg1/n";
  close fh;
}

你们很亲近.

在 Perl 中,子例程是使用 sub 关键字创建的(注意小写的 's').

In Perl, subroutines are created with the sub keyword (note the lowercase 's').

换行符是\n,而不是/n.

现在,我们喜欢使用词法变量作为文件句柄(这还有其他好处,当变量超出范围时会自动关闭文件).

These days, we like to use lexical variables as filehandles (this, among other advantages, will automatically close the file as the variable goes out of scope).

使用 > 作为文件模式将在每次打开文件时创建一个新的空文件.所以它只会包含添加的最后一条消息.切换到 >> 将附加消息.

Using > as the file mode will create a new, empty file each time you open the file. So it will only ever contain the last message added. Switching to >> will append the messages.

您应该检查调用 open() 的返回值,如果失败则采取适当的措施(通常杀死程序是最好的选择).

You should check the return value from your call to open() and take appropriate action if it fails (usually killing the program is the best option).

您应该在某处声明和定义 $message_file.由于子例程访问外部变量是一个坏主意,因此您可能希望在子例程内部这样做.

You should declare and define $message_file somewhere. As it's a bad idea for a subroutine to access external variables, you probably want to do that inside the subroutine.

但你最大的问题是线路:

But your biggest problem is the line:

sub filemessage ($arg1)

传统上,Perl 的子程序参数是通过一个名为 @_ 的数组传递的,您需要自己提取它们.

Traditionally Perl's subroutine parameters are passed in an array called @_ and you need to extract them yourself.

my ($arg1) = @_;

但是从 Perl 5.20 开始,有一个实验性的 signatures 功能可以按照您的预期工作.

But since Perl 5.20, there is an experimental signatures feature that works how you expect it to.

把所有这些放在一起,我们最终得到这个:

Putting all that together, we end up with this:

# turn on signatures (put this with the other "use"
# statements at the top of your file).
use experimental 'signatures';

sub filemessage ($arg1) {
  my $message_file = 'log.txt';

  open(my $fh, '>>', $message_file)
    or die "Can't open [$message_file]: $!\n";

  print $fh "$arg1\n";
} 

这篇关于Perl 将变量传递给子程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆