命令行上的perl哈希语法错误

时间:2014-12-21 18:57:18

标签: perl hash

当我在命令行中尝试哈希时,如下例所示,我收到语法错误。我尝试使用胖逗号但仍然是相同的结果。有人能帮助我吗?

perl -e "%hash_ex=(as,wdesadc,afcsdc,esvdfvzdfvfv,1,sd,34,34);print $hash_ex{'1'};"
syntax error at -e line 1, near "};"
Execution of -e aborted due to compilation errors.

perl -e "%hash_ex=('a' => 1 , 'b' => 2);print $hash_ex {a};"
syntax error at -e line 1, near "};"
Execution of -e aborted due to compilation errors.

2 个答案:

答案 0 :(得分:3)

问题是你的Shell还会替换以$开头的变量:

# (on zsh and bash)
echo "%hash_ex=(as,wdesadc,afcsdc,esvdfvzdfvfv,1,sd,34,34);print $hash_ex{'1'};" 
%hash_ex=(as,wdesadc,afcsdc,esvdfvzdfvfv,1,sd,34,34);print {'1'};

因此,您最好将单个qotes用于-E参数:

perl -e'%hash_ex=(as,wdesadc,afcsdc,esvdfvzdfvfv,1,sd,34,34);print $hash_ex{1};'
sd

如果你真的需要单引号(在这种情况下你不是),你可以使用q运算符:

perl -E'say q~some non-interpolating string\t\n$_~'
some non-interpolating string\t\n$_

或者您可以尝试避免插入shell:

perl -e "%hash_ex=(as,wdesadc,afcsdc,esvdfvzdfvfv,1,sd,34,34);print \$hash_ex{'1'};"

答案 1 :(得分:2)

您正在使用双引号将命令传递给Perl。这意味着shell首先会在字符串中插入任何变量,然后再将命令传递给Perl。你可以看到这个,如果你只用双引号然后单引号对字符串运行echo。 echo的输出将显示shell传递给Perl的内容

当shell处理双引号中的文本时,它会插入$ hash_ex。由于这没有在shell中设置,因此无需插值就意味着你的print语句而不是

print $hash_ex{a}

变为

print {a}

所以你需要将所有perl包装在singleqotes中,这样shell就不会插入任何变量并将整个字符串作为文字字符串传递给perl。