in reply to split line and populate hash shortcut ?

Rather than split, use a regex to extract the key and value and also skip any non-matching lines.

#! perl -slw use strict; use Data::Dumper; my %config; m[^([^#][^=]+)=(.*)$] and $config{ $1 } = $2 while <DATA>; print Dumper \%config; __DATA__ THIS=that name=joe height=heyman #this is a comment age=14

You might want to expand that a little and incorporate warnings about non-matching, non-blank, non-comment lines?


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: split line and populate hash shortcut ?
by traveler (Parson) on Feb 14, 2006 at 18:21 UTC
    Or
    m[^([^#][^=]+)=([^#\n]*)] and $config{ $1 } = $2 while <DATA>;
    To allow end of line comments and remove newlines from the "value" part. Removing trailing spaces is left as an exercise to the reader :-)
Re^2: split line and populate hash shortcut ?
by blokhead (Monsignor) on Feb 14, 2006 at 19:39 UTC
    my %config; m[^([^#][^=]+)=(.*)$] and $config{ $1 } = $2 while <DATA>;
    You could even write this as:
    my %config = map { /^([^#][^=]+)=(.*)$/ } <DATA>;
    There is an example somewhere in the perldocs that gives essentially the same technique for parsing simple config files, though I can't find it right now. I always thought it was ingenius & wonderfully succinct. It certainly applies nicely here.

    blokhead

Re^2: split line and populate hash shortcut ?
by leocharre (Priest) on Feb 14, 2006 at 18:10 UTC
    ooohh... i like i like... obviously the right thing to do! :) Thank you!