
bill1234
Novice
Jan 28, 2013, 8:48 AM
Post #5 of 9
(1979 views)
|
Re: [BillKSmith] Parsing data from a file with split & regex
[In reply to]
|
Can't Post
|
|
It is very hard to get a parser right without more info about the syntax. This does your example: use strict; use warnings; use Readonly; Readonly::Scalar my $SEPARATOR => q(|); my $Infile = <DATA>; my @fields = $Infile =~ /([\w ]+="[\w ]+")/g; my %output_hash; foreach my $field (@fields) { my ($label, $value) = $field =~ /([\w ]+)="([\w ]+)"/; $output_hash{$label} = $value; } print join( $SEPARATOR, keys %output_hash), "\n"; print join( $SEPARATOR, values %output_hash), "\n"; __DATA__ employee name="Steve" employee phone="5551234123" employee address="1234 street" This worked great. I'm running into problems though reading the data from a file. Using the following i was able to get it to print to file using <DATA> as the input, but when i tried to read it from a file it ends up printing no data. use strict; use warnings; use Readonly; use autodie; Readonly::Scalar my $SEPARATOR => q(|); my $filename2 = 'c:\test\test.txt'; open(my $fh1, '<', $filename2); my $Infile=$filename2; my @fields = $Infile =~ /([\w ]+="[\w ]+")/g; my %output_hash; my $filename = 'C:\test\test2.txt'; open my $fh, '>>', $filename or die "Cannot open '$filename' for reading: $!"; foreach my $field (@fields) { my ($label, $value) = $field =~ /([\w ]+)="([\w ]+)"/; $output_hash{$label} = $value; } print $fh join( $SEPARATOR, keys %output_hash), "\n"; print $fh join( $SEPARATOR, values %output_hash), "\n"; #__DATA__ #name="Steve" phone="5551234123" address="1234 street"
|