问题描述
我需要在bash shell上执行以下代码:
I need to execute the following code on a bash shell:
mogrify -resize 800x600 *JPG
由于宽度和高度是可变的,因此我尝试了以下操作:
Since the width and height are variables, I tried this:
`mogrify -resize $widx$hit *JPG`
但是在编译中,我得到一个错误,即全局符号 $ widx在getattach.pl第131行需要显式的程序包名称。,这是因为不是$ wid和x分开,编译器将$ widx视为未声明的新变量。
However in compilation, I get the error that Global symbol "$widx" requires explicit package name at getattach.pl line 131., which is because instead of $wid and x seperately, the compiler sees $widx as a new undeclared variable.
我尝试在反引号内插入双引号,但是代码的执行停止了,没有任何消息。
I tried inserting double quotes inside the backticks, but execution of code stopped without any messages.
在反引号中插入变量名以执行Shell的正确方法是什么?可以将它们串联吗?
What's the proper way of inserting variable names in backticks for shell execution? Can they be concatenated?
推荐答案
要将变量插入任何插值字符串中(例如 qq // 或 qx 或 qr // ),只做这就是$ foo! 就足够了:变量名(此处为 $ foo )由分隔! / code>不能是普通变量名的一部分。
To insert a variable into any interpolating string (be it qq// or qx or qr//), just doing "this is $foo!" is sufficient: The variable name (here: $foo) is delimited by the ! which cannot be part of a normal variable name.
用Perl的命名将字符串的一部分作为名称的一部分并不是一件容易的事。规则。示例:
It is not so easy when parts of the string could be part of the name by Perl's naming rules. Example:
my $genes = "ACTG$insert_genes_hereACTG";
Perl认为变量名称为 $ insert_genes_hereACTG 。可以通过
Perl considers the variable name to be $insert_genes_hereACTG. This can be solved by
-
使用curlies来分隔名称来解决:
Using curlies to delimit the name:
my $genes = "ACTG${insert_genes_here}ACTG";
这始终有效,并且是一种灵活的解决方案
This always works and is a flexible solution
连接字符串:
my $genes = "ACTG" . $insert_genes_here . "ACTG";
这对于非 qq -报价。一种解决方案是创建一个包含整个字符串的临时变量,然后将其内插为特殊引号:
This is a bit difficult for non-qq-quotes. A solution is to create a temporary variable that holds the whole string, and then interpolates it into special quotes:
my $command = "mogrify -resize " . $wid . "x" . $hit. " *JPG"; `$command`;
此方法的一种变体是使用 sprintf 内插:
A variant of this is to use sprintf interpolation:
my $command = sprintf 'mogrify -resize %dx%d *JPG', $wid, $hit;
顺便说一句,许多shell插值问题可以被 not 使用反引号规避,而是使用 open 或 system 来规避(取决于是否
As an aside, many shell interpolation problems can be circumvented by not using backticks, and using open or system instead (depending on whether or not you need output).
打开 :
open my $command, "-|", "mogrify", "-resize", $wid . "x" . $hit, glob("*JPG") or die ...; while (<$command>) { do something }
完全规避了外壳程序(而直接是 exec s),因此必须手动完成遍历。对于具有多个参数的 system 也是一样。
This completely circumvents the shell (and rather execs directly), so globbing has to be done manually. The same holds true for system with more than one argument.
这篇关于如何在反引号中正确使用perl变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!