----- Original Message -----
From: "Bill Stennett - compuserve" <[EMAIL PROTECTED]>
To: "activeperl mailing list" <[email protected]>
Sent: Thursday, June 15, 2006 3:42 PM
Subject: regex to parse name=value pairs from a string
Hi All,
I have a string formatted like this:
my $mystring = 'var1=123::var2=abc456::var3=10.99::var4=def';
What I need to do is to be able to extract name=value. I cannot be sure
where in the list a any value will occur so to extract a value for 'var2'
from the above example would require matching either:
'::var2=abc456::'
or
'var2=abc456::'
or
'::var2=abc456'
Can anyone suggest a regex to do this?
Maybe is possible to write it better but I will think up this:
#!/usr/bin/perl -w
use strict;
my $mystring = 'var1=123::var2=abc456::var3=10.99::var4=def';
my $valueforvar2;
%{$valueforvar2} = strtohash($mystring);
foreach (keys %{$valueforvar2}) {
print "$_=$valueforvar2->{$_}\n";
}
sub strtohash {
my $string = shift;
my @pairs = split(/::/,$string);
my %hash;
foreach (@pairs) {
my ($key,$val) = split(/=/,$_);
%hash->{$key} = $val;
}
return %hash;
}
Petr Vileta, Czech republic
(My server rejects all messages from Yahoo and Hotmail. Send me your mail
from another non-spammer site please.)
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs