質問

How can I use a Perl variable inside a XPath expression using the XML::LibXML module's findnodes() function? This is what I got:

my $variable = 1;
foreach my $node1 ($doc->findnodes('par/par1/par2[@id = $variable]'))
{

}

But it doesn’t seem to work. Thanks.

役に立ちましたか?

解決

You cannot interpolate using single quotes, you must use double quotes, or another form of quoting that does interpolate

"par/par1/par2[\@id = $variable]"

However, I assume that @id is not a variable, so you must escape its sigil, or it will be treated as a variable as well. If you are using use strict -- which you always should -- this will lead to a compiler error.

The other forms of quoting that might be mentioned

  • qq(), which is exactly like double quote
  • Heredocs

他のヒント

edit: kudos to TLP

Haritz,

Does changing the single quotes around the XPath expression to double quotes work?

I came here looking for exactly the same solution and I tried it in one of my scripts and I think it works the same with double quotes instead of single quotes, but I'm interested to know if it works for you too.

my $variable = 1;
foreach my $node1 ($doc->findnodes("par/par1/par2[\@id = $variable]"))
{

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top