Dexter
Dexter

Reputation: 1337

Split string and store in hash in perl

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

Answers (2)

xxfelixxx
xxfelixxx

Reputation: 6602

Although using a regular expression will work here, you should consider using Getopt::Long for any non-trivial command line argument parsing.

perldoc Getopt::Long

Upvotes: 0

Borodin
Borodin

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;

output

{
  a => undef,
  data => "num",
  empty => "",
  is => undef,
  string => 8,
  test => 2,
  value => 1,
}

Upvotes: 1

Related Questions