2

I am trying to pass Multiple Values to an Command line Argument as -cmd 'cp abc def' 'ls abd/def/ghi' etc ... and wanted to store these individually as an element of an array. I can take this to a string and use split function. i am trying to achieve the same using GetOptions. I am not sure of the reason it provides the size of the array. please help me with this.

use strict;    
use warnings;    
use Getopt::Long;    

my( $cmd ,$pro, $dom );      

GetOptions ( 'pro=s' => \$pro ,   
             'dom=s' => \$dom ,    
             'cmd=s@{1,}' => \$cmd );     



print $pro."\n".@$cmd."\n".$dom."\n" ;     

-->./abc.pl -pro JKFK -cmd 'ls abc/bcd/def' 'cp abn/cdf ads' -dom ABC        


Expected:     
JKFK    
['ls abc/bcd/def','cp abn/cdf ads']    
ABC    

Actual Results :    
JKFK    
2    
ABC  

I am trying to get these system commands users provide and those commands directly go to DB tables. I am trying to store those system commands as it is as an element in array so that it would be easy to parse and Insert into DB table. Please help me put them into array.

Thanks.

PCM
  • 21
  • 2
  • I had tried 'cmd=s' => \$cmd and then ./abc.pl -pro JKFK -cmd 'ls abc/bcd/def;cp abn/cdf ads' -dom ABC after that i had used split(";",$cmd) which resulted in an array but i like to know the solution using GetOptions – PCM Jan 25 '19 at 22:08

2 Answers2

6

You're evaluating an array in scalar context:

print $pro."\n".@$cmd."\n".$dom."\n" 

Try:

print $pro."\n@$cmd\n".$dom."\n"

In other words, use interpolation, which, for arrays, is equivalent to join($", @array) - where $" defaults to a space. This means you could use the following:

print $pro."\n".join(' ', @$cmd)."\n".$dom."\n" 
ikegami
  • 367,544
  • 15
  • 269
  • 518
Tanktalus
  • 21,664
  • 5
  • 41
  • 68
1

Your output method does not in any way suggest the brackets in the output you want.

print join("\n", $pro, "[ '" . join("', '", @$cmd) . "' ]", $dom, "");

or

use Data::Dump; # This is a CPAN module that's not normally installed by default

dd $pro, $cmd, $dom;
Ed Grimm
  • 548
  • 5
  • 13
  • With the code of yours the output is this JKFK [ ls abc/bcd/def cp abn/cdf ads ] ABC – PCM Jan 31 '19 at 16:35