linux - Perl - 如何将输入拆分为数组?

标签 linux perl

我有一个小的 Perl 脚本,用于获取用户命令行输入,然后将输入拆分为一个数组,其中每个服务 都应该是它自己的元素。

我的目标是启用单个参数,以及使用分隔字符启用多个参数,其中每个参数都用逗号分隔。这些例子是:

  • ssh
  • ssh,named,cups

我的代码如下所示,它编译没有错误,但输出不是预期的。

    print "Please provide the service name that you wish to analyze (Named service):\n";
    print "Several services may be provided, using a comma sign as a separator.\n";

    my $service_name_input = <>;
    chomp($service_name_input);
    my @service_list = split(/,/, $service_name_input);

    foreach my $line (@service_list)
    {
        open(my $service_input, "service @service_list status|");
    }

    foreach my $line (@service_list)
    {
        #Matches for "running".
        if ($line =~ m/(\(running\))/)
        {
            print "The service @service_list is running\n";
        }
        #Matches for "dead".
        elsif ($line =~ m/(dead)/)
        {
            print "The service @service_list is dead\n";
        }
    }

如果服务正在运行或停止,程序应该输出,但我只得到以下错误代码。当手动发出 service 命令时,它工作得很好。

The service command supports only basic LSB actions (start, stop, restart, try-restart, reload, force-reload, status). For other actions, please try to use systemctl.

对于我为实现工作计划应采取的步骤提供的任何帮助,我们将不胜感激。感谢您的阅读。

最佳答案

foreach my $line (@service_list)
{
    open(my $service_input, "service @service_list status|");
}

这个循环不使用$line。您将整个数组 @service_list 传递给服务命令,即您正在运行 service ssh named cups status。这会导致错误,因为 service 认为您要对 ssh 服务执行 named 操作。要解决这个问题,请编写 "service $line status |"

但是还有另一个问题:您也永远不会对 $service_input 做任何事情。如果你想遍历每个服务命令输出的每一行,你需要更像:

foreach my $service (@service_list)
{
    open(my $service_input, '-|', 'service', $service, 'status')
        or die "$0: can't run 'service': $!\n";

    while (my $line = readline $service_input)
    {
        #Matches for "running".
        if ($line =~ m/(\(running\))/)
        {
            print "The service $service is running\n";
        }
        #Matches for "dead".
        elsif ($line =~ m/(dead)/)
        {
            print "The service $service is dead\n";
        }
    }
}

我已经将您的 open 行更改为使用单独的模式参数 -| (这通常是很好的风格)和进程打开的列表形式,这避免了shell,一般来说也很好(例如,$service 中的“特殊字符”没有问题)。

关于linux - Perl - 如何将输入拆分为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31952309/

相关文章:

bash - 如何在 Perl 中使用 Shell 参数扩展?

regex - 查找仅匹配同一字符的两个实例的单词

linux - 解析日志以查找每个用户的所有源 IP 的最快方法

php - 如何在基于 Linux 的 Web 服务器上安装 wkhtmltopdf 0.12.0 及更高版本?

linux - 用于本地(非远程)命令执行的 ssh 隧道

java - Eclipse 自动填充一些无效标签

perl - AnyEvent fork_call 和 ping

perl - 使用 Perl 的 WWW::Mechanize 发送自定义 cookie(并查看自然设置的 cookie)

perl - 如何在perl中添加警告蜂鸣声

mysql - 禁用外键检查删除 InnoDB 表 Perl 脚本