Thomson
Thomson

Reputation: 21694

Pass command line parameters to perl via file?

Could command lines parameters been saved to a file and then pass the file to perl to parse out the options? Like response file (prefix the name with @) for some Microsoft tools.

Upvotes: 0

Views: 145

Answers (2)

Schwern
Schwern

Reputation: 165546

I am trying to pass expression to perl via command line, like perl -e 'print "\n"', and Windows command prompt makes using double quotes a little hard.

There are several solutions, from most to least preferable.

Write your program to a file

If your one liner is too big or complicated, write it to a file and run it. This avoids messing with shell escapes. You can reuse it and debug it and work in a real editor.

perl path\to\some_program

Command line options to perl can be put on the otherwise useless on Windows #! line. Here's an example.

#!/usr/bin/perl -i.bak -p

# -i.bak Backs up the file.
# -p Puts each line into $_ and writes out the new value of $_.
# So this changes all instances in a file of " with '.
s{"}{'}g;

Use alternative quote delimiters

Perl has a slew of alternative ways to write quotes. Use them instead. This is good for both one liners as well as things like q[<tag key='value'>].

perl -e "print qq[\n]"

Escape the quote

^ is the cmd.exe escape character. So ^" is treated as a literal quote.

perl -e "print ^"\n^""

Pretty yucky. I'd prefer using qq[] and reserve ^" for when you need to print a literal quote.

perl -e "print qq[^"\n]"

Use the ASCII code

The ASCII and UTF-8 hex code for " is 22. You can supply this to Perl with qq[\x22].

perl -e "print qq[\x22\n]"

Upvotes: 2

Hellmar Becker
Hellmar Becker

Reputation: 2982

You can read the file into a string and then use

    use Getopt::Long qw(GetOptionsFromString);
    $ret = GetOptionsFromString($string, ...);

to parse the options from that.

Upvotes: 0

Related Questions