http://www.perlmonks.org?node_id=134504

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

Hey.

I'm rewriting some horrible void-context mapping, and have stumbled upon a few...stumbling blocks :) I'm trying to parse a newline delimited config file, and populate an array and a hash with its contents. The file is basically a flat newline-delimited list containing URLs. This makes parsing slightly easier as we can ignore whitespace (URLs are encoded).

The problem is with comments. I want to ignore everything after a comment, and ignore lines that are made blank because of this. (Basically, I want to parse off comments in the same way the Perl parser does, only with the added bonus of being able to ignore whitespace.) The array should be every enabled line in the file (lines not commented out), and the hash should be keyed with every line in the file, ignoring whether or not it's commented out (effectively stripping comment characters from the line), and the values could be anything (I plan to use it as a lookup hash). I came up with this draft:

#!/usr/bin/perl -w use Data::Dumper; my %alllines; # hash: line => (arbitrary value) my @enabled_lines; # array: flat list while (<DATA>) { chomp; # not testing with defined as '0' couldn't be a valid url. my ($data) = /([^\s#]+)/; # this $alllines{$data} = 1 if $data; # works my ($enabled) = /([^\s#]+)#/; # this push @enabled_lines, $enabled if $enabled; # doesn't wo +rk } print Dumper(\%alllines); print Dumper(\@enabled_lines); __DATA__ astandardline #acommentedoutline # alinewithspacesbeforeandafterthecommentcharacter therealdata # a subordinate comment, this contains whitespa +ce as it should be ignored linewherethetabsshouldbeignored alinewith # multiple # comment # characters

%alllines gets populated fine, and just as I expected (here I used 1 as the values for the hash). @enabled_lines doesn't work, though; it's always a null list when it's printed. I expect I am missing something simple here, probably to do with my regex, although that one looks okay to my eyes. Aid?



--
my one true love