如何在字符串中扩展哈希变量?

时间:2012-10-05 18:21:06

标签: perl

如果字符串中的变量是简单的标量,例如使用正则表达式的“$ foo = 5”,我已经找到了这样做的方法。但问题是如果字符串中的变量是: $ foo-> {bar}等于5。

所以示例字符串是:

“这是一个哈希值为$ foo-> {bar}”的字符串。

如何将其扩展为:

“这是一个哈希值为5”的字符串

感谢。

编辑以获得更多解释:

我有一个字符串文字(我相信?我不是最好的词汇),这是我从某些文字来源收到的“Lorem Ipsum $ foo-> {bar} Lorem Ipsum”。我想取这个字符串,用我代码中变量的实际值替换所有变量名。

2 个答案:

答案 0 :(得分:4)

你所拥有的是一个“模板”。因此,您正在寻找模板系统。

假设这些引号实际上不在字符串中,我知道唯一能够理解模板语言的模板系统是String::Interpolate

$ perl -E'
   use String::Interpolate qw( interpolate );
   my $template = q!This is a string with hash value of $foo->{bar}!;
   local our $foo = { bar => 123 };
   say interpolate($template);
'
This is a string with hash value of 123

如果引号是字符串的一部分,那么你所拥有的是Perl代码。因此,您可以通过执行字符串获得所需的内容。这可以使用eval EXPR完成。

$ perl -E'
   my $template = q!"This is a string with hash value of $foo->{bar}"!;
   my $foo = { bar => 123 };
   my $result = eval($template);
   die $@ if $@;
   say $result;
'
This is a string with hash value of 123

我强烈建议不要这样做。我也没有特别找到String :: Interpolate。 Template::Toolkit可能是模板系统的热门选择。

$ perl -e'
   use Template qw( );
   my $template = q!This is a string with hash value of [% foo.bar %]!."\n";
   my %vars = ( foo => { bar => 123 } );
   Template->new()->process(\$template, \%vars);
'
This is a string with hash value of 123

答案 1 :(得分:-2)

这应该有效:

$foo->{"bar"} = 5;
printf "This is a string with hash value of $foo->{\"bar\"}]";
相关问题