On Wed, Sep 24, 2008 at 2:25 PM, Dan Fish <[EMAIL PROTECTED]> wrote:

> I've got a data file with a bunch of key/value pairs in the format
> "key=value;".  There may be only one to a line, or there may be several.  I
> know I can figure out how to do this using split, but I thought surely
> there
> must be a more "elegant" solution.  I was trying to do this using the
> following, but I must be misunderstanding how the "g" modifier works.
>
>
>
> use strict;
>
>
>
> my $str1 = "foo=bar;";
>
> my $str2 = "okey=dokey;file=a file name with spaces;yourkey=mykey;";
>
>
>
> parsekeys($str1);
>
> parsekeys($str2);
>
>
>
> sub parsekeys { my ($str) = @_;
>
>  while ($str =~ m/(.*)=(.*);/g){
>
>    print("$1,$2\n");
>
>  }
>
> }
>
>
>
> This prints:
>
>
>
> foo,bar
>
> okey=dokey;file=a file name with spaces;yourkey,mykey
>
>
>
> when what I'm really looking for is:
>
>
>
> foo,bar
>
> okey,dokey
>
> file,a file name with spaces
>
> yourkey,mykey
>
>
>
> Any help appreciated!
>
> Thanks, -Dan
>
> try this subroutine:

sub parsekeys {
# my ($str) = @_;
        my $str = shift;
        my %pairs  = ($str =~m/([^=]*)=([^;]*);/g);

        while (my ($key, $value) = each %pairs) {
                print $key,",", $value,"\n";
        }



# while ($str =~ m/(.*)=(.*);/g){

#   print("$1,$2\n");

}

for more information
perldoc perlretut

Reply via email to