Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract and save values from an XML file in Perl?

Tags:

shell

xml

perl

Here is what I am trying to do in a Perl script:

$data="";
sub loadXMLConfig()
{
     $filename="somexml.xml"
     $data = $xml->XMLin($filename);
}

sub GetVariable()
{
     ($FriendlyName) = @_;
     switch($FriendlyName)
     {
         case "My Friendly Name" {print $data->{my_xml_tag_name}}
         ....
         ....
         ....
      }
}

The problem is I am using Perl just because I am reading from an XML file, but I need to get these variables by a shell script. So, here is what I am using:

$ perl -e 'require "scrpt.pl"; loadConfigFile(); GetVariable("My Variable")' 

This works exactly as expected, but I need to read the XML file every time I am getting a variable. Is there a way I could "preserve" $data across shell calls? The idea is that I read the XML file only once. If no, is there is a more simple way I could do this? These are the things I can't change:

  • Config File is an XML
  • Need the variables in a shell script
like image 560
Freddy Avatar asked Feb 27 '23 03:02

Freddy


1 Answers

When I need some information, retrieved by Perl, in a shell script, I generate shell script by Perl and set environment variables via eval:

myscript

#!/bin/bash
BINDIR=`dirname $0`
CONFIG=$BINDIR/config.xml
eval `$BINDIR/readcfg $CONFIG`
echo Running on the $planet near the $star.

readcfg

#!/usr/bin/perl
use XML::Simple;
my $xml = XMLin('config.xml', VarAttr => 'name', ContentKey => '-content');
while (my ($k, $v) = each %{$xml->{param}}) {
    $v =~ s/'/'"'"'/g;
    $v = "'$v'";
    print "export $k=$v\n";
}

config.xml

<config>
    <param name="star">Sun</param>
    <param name="planet">Earth</param>
</config>
like image 154
codeholic Avatar answered Mar 24 '23 10:03

codeholic