I have a string
"myhashkey?key1=val1&key2=val2&key3=val3&key4=val4"
that I want to explode into
myhashkey => {
key1 => val1,
key2 => val2,
key3 => val3
}
I also want to collapse this back to the same string.
So far what I’ve come up with is pretty messy, using index and trying to build the values by hand
$arg = $_[0];
#if arg has = it may be key=val string
if(index($arg,'=') > -1 ){
#if arg has & character it might be key=val&key1=val
if(index($arg,'&') > -1 ){
#$arg =~ m/[=&\?]/
@r = split(/[=&\?]/,$arg);
my $hashkey = shift(@r)
my %values = @r;
return $class->$orig( key => $k, $value => \%values );
...
}else{
@r = split('=',$arg);
return ( key => $r[0], $value => $r[1] );
}
}
I don’t know how expensive the index(), split(), and join() functions are vs other methods of accomplishing this. I was thinking maybe I could use map + grep but I wasnt sure how to create the rergex for grep.
I also don’t want to reinvent the wheel so hopefully someone has a better idea of how to do this.
updated
BTW This is happening in the Moose BUILDARGS sub, so I don’t want to use a module like URI to parse the string everytime.
This is how I’m using the function in BUILDARGS
my $w = My::Param->new( 'hashkey?key1=val1&key2=val2&key3=val3');
my $x = My::Param->new( key => 'x', value => '7' );
my $y = My::Param->new( 'y=123' );
Produces this on print Dumper(*)
{ 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' }
bless( { 'key' => 'hashkey', 'meta_info' => [ #0 'hashkey?key1=val1&key2=val2&key3=val3' ], 'value' => { 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3' } }, 'My::Param' )
bless( { 'key' => 'x', 'meta_info' => [ #0 'key', #1 'x', #2 'value', #3 '7' ], 'value' => '7' }, 'My::Param' )
bless( { 'key' => 'y', 'meta_info' => [ #0 'y=123' ], 'value' => '123' }, 'My:Param' )
In this case, the already invented wheel is named URI