perl - 如何在 shell 脚本中处理 Perl 数组元素?

标签 perl bash

例如:

在 Perl 中:

@array = (1,2,3);

system ("/tmp/a.sh @array" ); 

在我的 shell 脚本中,如何在 shell 脚本中处理这个数组?如何处理 shell 脚本以接收参数,以及如何在 shell 脚本中使用该数组变量?

最佳答案

这个:

my @array = (1,2,3);   
system ("/tmp/a.sh @array" );

相当于shell命令:

/tmp/a.sh 1 2 3

您只需打印出传递给系统的内容即可看到这一点:

print "/tmp/a.sh @array";

a.sh 应该像处理任何其他 shell 参数集一样处理它们。

为了安全起见,您应该绕过 shell 并直接将数组作为参数传递:

system "/tmp/a.sh", @array;

这样做会将 @array 的每个元素作为单独的参数而不是空格分隔的字符串传递。如果 @array 中的值包含空格,这一点很重要,例如:

my @array = ("Hello, world", "This is one argument");
system "./count_args.sh @array";
system "./count_args.sh", @array;

其中 count_args.sh 是:

#!/bin/sh

echo "$# arguments"

您会看到第一个参数有 6 个参数,第二个参数有 2 个。

有关在 shell 程序中处理参数的简短教程可以在 here 中找到。 .

无论如何,为什么要用 Perl 编写一个程序,而用 shell 编写一个程序呢?使用两种语言会增加复杂性,而且 shell 没有调试器。它们都用 Perl 编写。更好的是,将其编写为 Perl 程序中的函数。

关于perl - 如何在 shell 脚本中处理 Perl 数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2911192/

相关文章:

windows - 如果在多行替换中死亡,Perl 会报告错误的行号。这是预期的还是错误?

perl - Perl 脚本中子程序引用的分配

perl - 是否有所有 perl 状态运算符和修饰符的简洁列表?

xml - 用于更改 xml 元素的 shell 脚本

macos - 在 Coco 应用程序中使用外部 Perl 会被视为不好的做法吗?

perl - 这不是数组引用吗?为什么它不是数组引用?

git - Cygwin:git 的颜色编码和分支信息?

bash - AWS Session Manager 未获取 bashrc

使用 MagickWand C API 自定义浮雕

bash - 交换不同长度字符串中特定位置的字符