1

My XML:

< measValue dn="Cabinet=0, Shelf=0, Card=2, Host=0">

    < r p="1">1.42</r>

    < r p="2">2.28</r>

< /measValue>

I want to match getAttribute("dn") with different patterns like

1> Host=0 # this is very easy

my solution:

if (getAttribute("dn")=~ /Host=0/)

2> Host=0 && Card=2

I can do it but I need to match it twice like

if (getAttribute("dn")=~ /Host=0/) && (getAttribute("dn")=~ /Card=2/)

Is there any better way to accomplice this match this second pattern? using LibXML

Toto
  • 89,455
  • 62
  • 89
  • 125
marks
  • 45
  • 4

2 Answers2

1

Have a try with:

if (getAttribute("dn")=~ /^(?=.*\bHost=0\b)(?=.*\bCard=2\b)/)

The word boundaries \b are here to avoid matching myHost=01 and everything similar.

Toto
  • 89,455
  • 62
  • 89
  • 125
0

Your approach has the problem that getAttribute("dn") =~ /Card=2/ would also match a value of Card=25 which is probably not what you want.

I would first write a helper that converts a string with key/value pairs into a hash:

sub key_value_pairs_to_hash {
    my $string = shift;
    my %hash;

    for my $pair (split(/\s*,\s*/, $string)) {
        my ($key, $value) = split(/\s*=\s*/, $pair, 2);
        $hash{$key} = $value;
    }

    return \%hash;
}

Then you can test the values like this:

my $hash = key_value_pairs_to_hash('Cabinet=0, Shelf=0, Card=2, Host=0');

if ($hash->{Host} == 0 && $hash->{Card} == 2) {
    print("match\n");
}
nwellnhof
  • 32,319
  • 7
  • 89
  • 113
  • make sense! But there is another pain, the number of attribute matches are variable here. I may get 2 values to match or just one value to match. i.e. I may get only Card to match or Host and Card both to match. Can I keep this in some array and match it once only for all? – marks Mar 27 '14 at 10:36
  • Yes, you can store the values to be matched in an array or a hash. If you have problems with that, please ask a separate question. – nwellnhof Mar 27 '14 at 10:45