如何使用 for 循环结果并使用 perl 中的 mailx 插入正文电子邮件

how to use the for loop result and insert in body email using mailx in perl

我有这段代码,我想使用我的 for 循环 say "$dir,$count"; 的结果放在我的电子邮件正文中。我的尝试是这个代码 email($dir.$count); 这是错误的。

#! /usr/bin/env perl

use feature qw(say);
use strict;
use warnings;
use Getopt::Long;

my $email="";
GetOptions("email=s" => $email);

{
    my $fn = parse_command_line_options();
    my $self = Main->new(
        infile => $fn
    );
    my $dirs = $self->parse_infile();
    for my $dir (@$dirs) {
        my $count = $self->count_files( $dir );
        say "$dir,$count";
    }
}
email($dir.$count);

sub parse_command_line_options {
    my $fn = 'list_dir.txt';
    GetOptions("infile=s" => $fn ) or die "Error in command line arguments\n";
    return $fn;
}


sub email {
    my $subj = "No of files in outbox folders";
    my $body = "These are the lists of directories with the no of files\n";
    open (MAIL, "|mailx -s \"$subj\" $email");
    print MAIL $body;
    close (MAIL);
}

my attempt is this code email($dir.$count); which is wrong.

这不是解释您遇到的问题的非常清晰的方式。你应该告诉我们为什么你认为这是错误的;您看到了什么意外行为。

运行 你的代码编译检查(perl -c),我得到这些错误:

Global symbol "$dir" requires explicit package name (did you forget to declare "my $dir"?) at testit line 22.
Global symbol "$count" requires explicit package name (did you forget to declare "my $count"?) at testit line 22.

但是,我们可以看到您 声明了这些变量。那么这里有什么问题?

您需要了解“范围界定”。并非所有变量在整个程序中都是可见的。变量可见的程序部分称为变量的范围。

对于使用 my 声明的变量,规则非常简单。该变量从声明它的位置到最内层封闭代码块的末尾都是可见的。为了解释这一点,让我们看一下您的代码的一部分。

{
    my $fn = parse_command_line_options();
    my $self = Main->new(
        infile => $fn
    );
    my $dirs = $self->parse_infile();
    for my $dir (@$dirs) {
        my $count = $self->count_files( $dir );
        say "$dir,$count";
    }
}
email($dir.$count);

在本节中,每对匹配的大括号 ({ ... }) 声明一个代码块。有一个块定义了每次循环执行的代码,还有另一个块围绕着您的大部分代码(只是省略了对 email() 的调用)。

您的 $count 变量在 for 循环内声明。所以它只在那个块内可见(它的范围是那个块)。 $dir 的规则稍微复杂一些。在 for 循环中声明的变量有一种特殊情况。它们被视为在循环块的开头声明,并且仅在该块内可见。还值得指出的是,对于这两个变量,每次循环时都会获得变量的新实例 - 因此每次新的循环迭代开始时,这些变量中的数据都会丢失。

这就是 Perl 说您的变量不存在的原因。这是因为它们只存在于循环块中,而您正试图在该块之外访问它们。

解决方案是将变量的声明移动到外部范围,或者将对子例程的调用移动到 for 块中。

修复该问题后您可能会遇到的其他几个问题:

  • 你真的是说 email($dir.$count) 吗? . 运算符连接两个变量。您可能指的是 email($dir, $count)
  • 您实际上并没有使用传递给子例程的值。

可能您正在寻找类似

的东西
# ...
{
    my $fn = parse_command_line_options();
    my $self = Main->new(
        infile => $fn
    );
    my @counts;
    my $dirs = $self->parse_infile();
    for my $dir (@$dirs) {
        my $count = $self->count_files( $dir );
        say "$dir,$count";
        push @counts, "$dir,$count"
    }
    email(@counts);
}

# ...

sub email {
    my $subj = "No of files in outbox folders";
    my $body = "These are the lists of directories with the no of files\n";
    open (MAIL, "|mailx -s \"$subj\" $email");
    print MAIL $body, "\n".join(@_);
    close (MAIL);
}