CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Regular Expressions:
look simple, finding tough to split

 



anilm
stranger

Feb 17, 2005, 6:49 AM

Post #1 of 4 (4034 views)
look simple, finding tough to split Can't Post

Hi,
It looks simple. finding tough to split a line.

LINE:
first=Andrew last=chapell time="2005:02:14 21:59:59" info="Successfully authenticated" userid=andrew src=45231
dst=3213

I was trying to extract the information from the above line in name=value pair using split(/\s+/$line);
And was getting a result

first=Andrew
last=chapell
time="2005:02:14
21:59:59"
info="Successfully
authenticated"
userid=andrew
src=45231
dst=3213

Please help me.


davorg
Thaumaturge / Moderator

Feb 17, 2005, 9:18 AM

Post #2 of 4 (4025 views)
Re: [anilm] look simple, finding tough to split [In reply to] Can't Post

Using split here is just making life far more difficult than necessary for yourself. Finding the right regex to use could take ages. It's the embedded spaces in some values that make it difficult.

Far easier to use the right tool for the job. And in this case, I think that's probably Text::ParseWords.


Code
 
use strict;
use warnings;

use Text::ParseWords;

my $line = 'first=Andrew last=chapell time="2005:02:14 21:59:59" info="Successfully authenticated" userid=andrew src=45231 dst=3213';

my %data = parse_line('[\s=]', 0, $line);

for (keys %data) {
print "$_ -> $data{$_}\n";
}


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


anilm
stranger

Feb 17, 2005, 10:34 AM

Post #3 of 4 (4022 views)
Re: [anilm] look simple, finding tough to split [In reply to] Can't Post

Hi Dave Cross,

Thanks a lot for the timely help.

regards
Anil


MrPJ
User

Feb 17, 2005, 11:34 AM

Post #4 of 4 (4020 views)
Re: [davorg] look simple, finding tough to split [In reply to] Can't Post

A quick attempt...


Code
my $line = 'first=Andrew last=chapell time="2005:02:14 21:59:59" info="Successfully authenticated" userid=andrew src=45231 dst=3213';  
my $last = 0;
my %temp = ();
my $past = '';

while ($line =~ /((\w+)=)/g) {
my $match_len = length $1;
my $start_pos = $last;
$last = pos $line;
$temp{$past} = substr($line, $start_pos, $last - $start_pos - $match_len) if ($past);
$past = $2;
}
$temp{$past} = substr($line, $last);

print "Content-type: text/plain\n\n";
print map { "$_ => $temp{$_}\n" } sort keys %temp;



(This post was edited by MrPJ on Feb 17, 2005, 11:35 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives