in reply to Parsing issue

This is most of the way there, but it will break if you have quoted commas in any of your values. A better (tho' slower) approach would be to build a real parser using something like Parse::RecDescent.

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; $_ = 'allow:test1,"@test 2 " deny:test3,test4 password:"123 456"'; my %hash = /(\w+):(.+?)(?:\s+(?=\w+:)|$)/g; foreach (keys %hash) { $hash{$_} = [ split /,/, $hash{$_} ] if $hash{$_} =~ /,/; } print Dumper \%hash;
--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re: Re: Parsing issue
by kabel (Chaplain) on Oct 08, 2002 at 12:34 UTC
    the package Text::ParseWords with its function quotewords is a very nice replacement for the "ordinary" split :-)

      Aha! You're absolutely right. I'd forgotten Text::ParseWords. In which case, replace my solution with this:

      #!/usr/bin/perl use strict; use warnings; use Text::ParseWords; use Data::Dumper; $_ = 'allow:test1,"@test 2 " deny:test3,test4 password:"123 456"'; my %hash = /(\w+):(.+?)(?:\s+(?=\w+:)|$)/g; foreach (keys %hash) { my @arr = parse_line(',', 1, $hash{$_}); $hash{$_} = \@arr if @arr > 1; } print Dumper \%hash;
      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you do not talk about Perl club."
      -- Chip Salzenberg

        This still breaks with an input string like
        $_ = 'allow:test1,"@test 2 " deny:test3,test4 password:"123 456", "h +ey, Doh:bad "';
        JJ