Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi to all, I'm wondering if it's possible to use dynamic paths to element in xml document. Now I'm using XML::Simple and I want to do something like this:

use XML::Simple; my $fh = IO::File->new('/root/regions.xml'); my $data = XML::Simple::XMLin($fh); $data->{root}->{configs}->$VAR->{region_prefix}

Or is there some other way, or workaround that will not require to rewrite whole script for for this?

Thanks in advance.

Replies are listed 'Best First'.
Re: Perl XML "dynamic paths "?
by daxim (Curate) on Aug 16, 2012 at 14:03 UTC
    What you wrote already works, you just need to correct the syntax:
    $data->{root}->{configs}->{$VAR}->{region_prefix}
    Better style:
    $data->{root}{configs}{$VAR}{region_prefix}
    PS: Future-proof your program by enabling strict mode. This ensures you get the same data structure even when the number of elements change.
      Thanks to you too, it helped.
Re: Perl XML "dynamic paths "?
by Corion (Patriarch) on Aug 16, 2012 at 13:54 UTC
      Sorry for the late answer. This is example of my config, a node number is the $VAR, in my case. I may need to use config options from <node3> or <nodeN>, that's why I need some sort of variable I guess.
      <?xml version='1.0'?> <regions> <node3> <instance_num>0</instance_num> <common_db_template>165.sql</common_db_template> <lib_db_template>165b.sql</lib_db_template> <region>node3</region> <region_db_host>192.168.38.1</region_db_host> <region_db_port>3306</region_db_port> <region_name>node3.test.com</region_name> <region_prefix>Nd3_</region_prefix> </node3> <node4> <instance_num>0</instance_num> <common_db_template>165.sql</common_db_template> <lib_db_template>165b.sql</lib_db_template> <region>node4</region> <region_db_host>192.168.22.1</region_db_host> <region_db_port>3308</region_db_port> <region_name>node4.test.com</region_name> <region_prefix>Nd4_</region_prefix> </node4> <node5> <instance_num>0</instance_num> <common_db_template>165.sql</common_db_template> <lib_db_template>165b.sql</lib_db_template> <region>node5</region> <region_db_host>192.168.1.1</region_db_host> <region_db_port>3306</region_db_port> <region_name>node5.test.com</region_name> <region_prefix>Nd5_</region_prefix> </node5> </regions>

        If all you need is one specific element of your path to change, then using ->{$VAR}-> already is enough. See Data::Dumper for getting output of a Perl data structure, and References Quick Reference for how to use references. References are what XML::Simple returns.