例如:
在Perl中:
@array = (1,2,3);
system ("/tmp/a.sh @array" );
Run Code Online (Sandbox Code Playgroud)
在我的shell脚本中,如何在shell脚本中处理这个数组?如何处理shell脚本以接收参数,以及如何在shell脚本中使用该数组变量?
这个:
my @array = (1,2,3);
system ("/tmp/a.sh @array" );
Run Code Online (Sandbox Code Playgroud)
相当于shell命令:
/tmp/a.sh 1 2 3
Run Code Online (Sandbox Code Playgroud)
你可以通过简单地打印出传递给系统的内容来看到这一点:
print "/tmp/a.sh @array";
Run Code Online (Sandbox Code Playgroud)
a.sh 应该像任何其他shell参数一样处理它们.
为了安全起见,您应绕过shell并直接将数组作为参数传递:
system "/tmp/a.sh", @array;
Run Code Online (Sandbox Code Playgroud)
这样做会将@arrayin的每个元素作为单独的参数传递,而不是作为空格分隔的字符串传递.如果@array包含空格中的值,这很重要,例如:
my @array = ("Hello, world", "This is one argument");
system "./count_args.sh @array";
system "./count_args.sh", @array;
Run Code Online (Sandbox Code Playgroud)
在哪里count_args.sh:
#!/bin/sh
echo "$# arguments"
Run Code Online (Sandbox Code Playgroud)
你会看到,在第一个中它获得6个参数,第二个获得2个参数.
无论如何,为什么要在Perl中编写一个程序,在shell中编写一个程序?它增加了使用两种语言的复杂性,shell没有调试器.用Perl写它们.更好的是,将其作为Perl程序中的函数编写.