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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks!my bad for asking a silly question here...that was easy it works with \b
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");
}

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.