Buddyhelp has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, Could you please help me with this.. I have to construct a string like
A|{NameTag}|Command|{Name}|{Parameters...}
Currently I have a code that does something close to this
my ($self,$nametag,$name,@params) = @_;#receives input from user my $tmp = { 'NameTag' => $nametag, 'Name' => $name, }; #i don't know how to extract the contents of @params and put it in the + $tmp hash my $InputRequest = $Obj->CreateString($tmp); } sub CreateString { ( my $self, my $hash ) = @_; $str = "A|" . $hash->{'NameTag'} . "|"."Command"."|" . $hash->{'Name'} . "|" return ($str); }

The problem is the user can send a command with multiple parameters in the form of an array like (a,b,c,d) the number of elements in the array may vary. HOw do I internally create a hash that can accomodate all the members of the array and concatenate it in the form a|b|c|d and put it in the form

A|{NameTag}|Command|{Name}|a|b|c|d

Please help.. I know only very basic perl.

Thank you

Replies are listed 'Best First'.
Re: Creating a dynamic hash from an array
by Athanasius (Archbishop) on Jun 08, 2012 at 15:01 UTC

    Hello Buddyhelp,

    If I understand your question correctly, you don’t need the hash at all. Simply code the subroutine as follows:

    sub CreateString { my ($self, $nametag, $name, @params) = @_; my $string = "A|$nametag|Command|$name"; $string .= "|$_" foreach @params; return $string; }

    and call it like this:

    my $InputRequest = $Obj->CreateString('tag-1', 'name-1', @params);

    HTH,

    Athanasius <°(((><contra mundum

Re: Creating a dynamic hash from an array
by stevieb (Canon) on Jun 08, 2012 at 15:56 UTC

    Not to take anything away from Athanasius post, but being Perl, timtowtdi :) Here's another potential solution.

    Instead of looking at it like you have to transform the array into key/value pairs in the hash, you can simply throw the array into the hash directly:

    my $tmp = { NameTag => $nametag, Name => $name, Params => \@params, };

    Then:

    sub CreateString { ( my $self, my $hash ) = @_; my $str = "A|" . $hash->{'NameTag'} . "|"."Command"."|" . $hash->{'Name'} . "|" . join( "|", @{ $hash->{ Params } } ); return ($str); }

    Update: In fact, you can also eliminate the need for the $tmp var entirely by calling your sub like this:

    my $InputRequest = $Obj->CreateString({ NameTag => $nametag, Name => $name, Params => \@params, });