Given an interesting parsing situation, I took it as a chance to explore conditional regexen. Essentially, I had a list of string value pairs, where the string might be followed by either a '=' or ':' character and where the value might be bare (numeric), bare but separated by spaces, or quoted with or without embedded spaces. And where the separating delimiter was a space. Quite legible to the eye, somewhat less so to a parser.
#!/perl/bin/perl
#
use strict;
use warnings;
use diagnostics;
$_ = qq(rated=0 lang="English" Channels: 0 1 250 interface="Version: 2
+.34.59.en");
print 'rated=',getvalue('rated',$_),"\n";
print 'lang=',getvalue('lang',$_),"\n";
print 'Channels: ',getvalue('Channels',$_),"\n";
print 'interface=',getvalue('interface',$_),"\n";
sub getvalue {
my $s = shift;
local $_ = shift;
my ($value1,$value2,$value3) = /
$s(?:=|:) # key word followed by either a '=' or ':' cha
+racter
(?(?=\d) # first case, '=' followed by a number
(\d+) # gather the digits into $1
| # or
(?(?=\") # second case, '=' followed by a quote
\"([^\"]+)\" # gather the string without the quotes into $2
| # or
\s(.*?)\s\D # default case, space followed by
# anything until space and non-digit into $3
) # end second conditional
) # end first conditional
/x;
if (defined($value1)) {
$value1;
}
elsif (defined($value2)) {
$value2;
}
elsif (defined($value3)) {
$value3;
}
else {
'No match found';
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.