harishnuti has asked for the wisdom of the Perl Monks concerning the following question:


Hello Monks,


I have a Typical requirement which includes Extraction of patterns from below chunk of text. My text to be splitted into key:value pairs as below..


################################

firstName : firstValue

Name2: Value2

Name3:Value3 Name4:value4

Name5: Name6:

################################

The above chunk of data , i should read as a name value pairs preferably in Hash or array.

iam trying to write a match pattern as below.
while (){ chomp($_); push(@splittedline,$+ ) while $_ =~m{ ([^\S\s*:\S\s*]*) }gx; } # Sorry iam poor in regular expressions # i tried several regular expressions, above gives error # and doesnt work properly # finally @splitted line should contain key value pairs # One might wonder what above is, my requirement is to # read the TNG scheduler output containing Jobs info # and nicely format into text document

Replies are listed 'Best First'.
Re: Selective String extraction & formatting
by moritz (Cardinal) on Jul 03, 2008 at 08:51 UTC
    use strict; use warnings; use Data::Dumper; my %h; while (<DATA>) { while (m/(\w+)\s?:\s?(\S*)/g){ $h{$1} = $2; } } print Dumper \%h; __DATA__ firstName : firstValue Name2: Value2 Name3:Value3 Name4:value4 Name5: Name6:

    Note that use of \w and \S is guesswork on my part - it works for the example you gave, but it depends on your data format if that's the right choice.

    Please only use <code>...</code> tags for code, put your question into normal paragraphs. See Writeup Formatting Tips.

      First of all i apologize for formatting, it was a typo on putting code tag, and secondly thx for the tip.

        The apology may be taken better if you fix the tags.