Getopt::Long getting a string with spaces into a variable

后端 未结 4 1143
旧时难觅i
旧时难觅i 2021-01-15 09:42

I\'m making a perl script which uses Getopt::Long to parse command line arguments. However, I have an argument which can accept a string (with spaces). How can I get the who

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-15 10:40

    This is really a reply to MaxMackie's question on Ernest's answer, but it's too long, so here goes:

    Your script never sees the quotes, only the shell that is passing the arguments. When you call a script (or program), what is happening on a lower level is that the command is called with several arguments in an array. The shell normally splits arguments up based on whitespace. What your program sees right now is:

    [0]./script.pl
    [1]--string=blah
    [2]blah
    [3]blah
    [4]blah
    [5]yup
    [6]--another-opt
    

    Putting quotes around the string or escaping it results in in this:

    [0]./script.pl
    [1]--string=blah blah blah blah yup
    [2]--another-opt
    

    Shells (bash in particular, others I'm sure) allows interspersing quotes without spaces as much as you like. ls -"l""h" is the same as ls -lh, hence you an do "--string=blah blah" or --string="blah blah". The parsing of the individual arguments with getopt that lets you put them out of order and use --long-name or -l happens after everything is turned into an array item and passed to the program. The shell has nothing to do with that.

提交回复
热议问题