Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Data parsing 1

Status
Not open for further replies.

travs69

MIS
Dec 21, 2006
1,431
US
id:2 name:test1 longname:test2 with space longname description:here is my description.id:10 name:test3 longname:test 4 long name description:a discription of test 5


I have data like above and I'd like to get it into a hash like
%hash { 'id:2' =>
{name => test1
longname => test2 with space longname
description => here is my description.},
'id:10' =>
{name => test3
longname => test 4 long name
description: a discription of test 5
}
}


I have tried a multitude of regex/splits and can't quit get it to split the way I want it to..

Thanks in advance


Travis

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
A suggestion to start with:
Code:
@fields=split/(id:|name:|longname:|description:)/;
shift@fields;
while($k=shift@fields){
  $v=shift@fields;
  $v=~s/\s+$//;
  if($k eq'id:'){
    $mainkey='id:'.$v;
  }else{
    $hash{$mainkey}{substr($k,0,-1)}=$v;
  }
}

: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Thanks.. I was struggling with that one for a bit, I figured I could figure out a split that would pick up the word before the : and then everything up to the word before the next :, but it was just killing me.... your seems so simple :)

Thanks!!!

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
If you wanted to use a regular expression....
Code:
#!perl

my $line = ('id:2 name:test1 longname:test2 with space longname description:here is my description.id:10 name:test3 longname:test 4 long name description:a discription of test 5');

my %hash;
while ($line =~ /id:(\d+)\s+name:(.*?)\s+longname:(.*?)\s+description:(.*?)(?=id:|$)/g ){
    $hash{id} = $1;
    $hash{name} = $2;
    $hash{longname} = $3;
    $hash{description} = $4;
print "\n";
foreach $key (keys(%hash)) { print "$key: $hash{$key}\n"; }
}

'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top