如何从Perl中的XML文件中提取和保存值?

前端之家收集整理的这篇文章主要介绍了如何从Perl中的XML文件中提取和保存值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我在Perl脚本中尝试做的事情:

$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}}
         ....
         ....
         ....
      }
}

   

问题是我使用Perl只是因为我正在读取XML文件,但我需要通过shell脚本获取这些变量.所以,这是我正在使用的:

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

这完全按预期工作,但每次获取变量时我都需要读取XML文件.有没有办法可以在shell调用中“保留”$data?我的想法是我只读了一次XML文件.如果不是,有没有更简单的方法可以做到这一点?这些是我无法改变的:

> Config File是一种XML
>需要shell脚本中的变量

解决方法

当我需要一些由Perl检索的信息时,在shell脚本中,我通过Perl生成shell脚本并通过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>

猜你在找的Perl相关文章