Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Textfile to csv with a small twist

by kvale (Monsignor)
on Aug 25, 2005 at 17:57 UTC ( [id://486671]=note: print w/replies, xml ) Need Help??


in reply to Textfile to csv with a small twist

Parsing with a state variable ($category in this case) is one way to remember which heading th text falls under:
use Data::Dumper; use strict; use warnings; my %parse_tree; my $category; while (my $line = <DATA>) { if ($line =~ /^(\w+:)$/) { $category = $1; $parse_tree{ $category} = []; } else { push @{$parse_tree{ $category}}, $line; } } print Dumper( \%parse_tree); __DATA__ heading1: text1 text2 text3 heading2: text4 text5 text6
yields
$VAR1 = { 'heading1' => [ 'text1 ', 'text2 ', 'text3 ' ], 'heading2' => [ 'text4 ', 'text5 ', 'text6 ' ] };
In the dumped hash, note that the newlines are preserved.

Update: altered the regex to capture the colon.

-Mark

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://486671]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 20:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found