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

i had perl script that takes input from commandline arguments ,but tle problem is while passing srtings with \n contained in it ,it ignores \n and treats it like normal character squence why its loosing its significance , iwant \n to have its effect on string later on ....

perl program.pl "hai hello\nhow r y" "i am fine" $string1=$Argv[0]; $string1=$Argv[1]; print $string1 ; print $string2 ; ###output##### hai hello\nhow r y i am fine Now------------------------------------------ $string1="hai hello\nhow r y"; $string1="i am fine"; print $string1 ; print $string2 ; ###output##### hai hello how r y i am fine

here nothing to do with second string,but the problem is i want the string taken from arguments to behave line the string in secon scenario ....Please help

Replies are listed 'Best First'.
Re: help regarding command line arguments
by roboticus (Chancellor) on Nov 18, 2014 at 12:35 UTC

    praveenchappa:

    When you use "\n" in a string in your script, perl converts the "\n" into the newline character. But you don't want perl to automatically do that in data, 'cause sometimes you really want the characters "\" and "n". When you pass data into your script, perl assumes the data is what you want, so it doesn't touch it.

    So if you want the "\n" converted into a newline, just tell perl to do the conversion for you, like so:

    use strict; use threads; my $t = shift; my $u = $t; $u =~ s/\\n/\n/g; print "<$t>\n\n<$u>\n";

    Which gives me this when I run it:

    $ perl zoop.pl "foo\nbar\n\n\nbaz" <foo\nbar\n\n\nbaz> <foo bar baz>

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: help regarding command line arguments
by rnewsham (Curate) on Nov 18, 2014 at 12:30 UTC

    Probably the simplest way would be to just replace the string \n with an actual \n.

    use strict; use warnings; for ( @ARGV ) { s/\\n/\n/g; } my $string1=$ARGV[0]; my $string2=$ARGV[1]; print $string1 ; print $string2 ;
Re: help regarding command line arguments
by Anonymous Monk on Nov 18, 2014 at 13:22 UTC
    The shell can send actual newline characters to Perl, rather than two characters, backslash followed by n.

    Unix (Bash):

    "Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard."
    perl program.pl $'hai hello\nhow r y' "i am fine"
    Powershell (Windows) uses backtick (`) rather then backslash for embedding special characters. I don't really remember how it works, so read it's documentation. I guess it's something like:
    perl program.pl "hai hello`nhow r y" "i am fine"
Re: help regarding command line arguments
by Sathishkumar (Scribe) on Nov 19, 2014 at 08:21 UTC
    Look this Getopt::Long module