Reputation: 1337
I have a string of the format :
my $string = "this -is -a -test=2 -value=1 -data=num -string=8";
Basically, this is a some sort of cmd line format where we have a option, followed by some value. I want to split this string so as to create a hash so as to store each option with its value.
my hash should look like :
my %hash = (
"this" => "",
"is" => "",
"test" => "2",
"string" => "8",
);
Can this be done in one single line in perl ?
Upvotes: 1
Views: 453
Reputation: 6602
Although using a regular expression will work here, you should consider using Getopt::Long
for any non-trivial command line argument parsing.
Upvotes: 0
Reputation: 126722
You can do this with a regular expression. Note that options without a value like is
will be stored as undef
, whereas options with an empty parameter like empty=
will be stored as a null string
Your parameter this
isn't found because it doesn't start with a hyphen -
use strict;
use warnings;
my $string = "this -is -a -test=2 -empty= -value=1 -data=num -string=8";
my %options = $string =~ /-(\w+)(?:=(\S*))?/g;
use Data::Dump;
dd \%options;
{
a => undef,
data => "num",
empty => "",
is => undef,
string => 8,
test => 2,
value => 1,
}
Upvotes: 1