tags:

views:

119

answers:

2

My file contains

a: b
d: e
f: a:b:c
g: a
   b
   c
   d
   f:g:h
h: d
   d:dd:d
J: g,j

How can I parse this file into lefthand side values into one array and right hand side to another array? I tried with split, but I am not able to get it back.

I want to store them into hash.

+2  A: 

Howzabout this:

#!/usr/bin/perl
use warnings;
use strict;
my $s = 
q/a: b
d: e
f: a:b:c
g: a
   b
   c
   d
   f:g:h
h: d
   d:dd:d
   f
/;
open my $input, "<", \$s or die $!;
my @left;
my @right;
while (<$input>) {
    chomp;
    my ($left, $right) = /^(.):?\s+(.*)$/;
    push @left, $left;
    push @right, $right;
}
print "left:", join ", ", @left;
print "\n";
print "right:", join ", ", @right;
print "\n";
Kinopiko
find changes in question ...
joe
Maybe there is enough information there for you to work out the rest yourself?
Kinopiko
i sloved it with this information
joe
+2  A: 

Why doesn't split work?

use strict;
use warnings;

open my $file, '<', 'file.txt';
my %hash;

while (my $line = <$file>) {

    my ( $left, $right ) = split /:/, $line, 2; # Splits only on the first colon
    $right =~ s/^\s+|\s+$//g;                   # Remove leading/ trailing spaces
    $hash {$left} = $right;                     # Populate hash
}

close $file;

# print to test the output
print (join ' => ', $_, $hash{$_}),"\n" foreach keys %hash;
Zaid
Odd that this is the accepted answer. From the question I was guessing that split didn't work because not every line has a leading field.
brian d foy
True, but it's difficult to ascertain what the OP needs then. It's a poorly-defined question
Zaid