user3816820
user3816820

Reputation: 37

Using double quotes in Perl script

Can anyone help in resolving this:

use strict;
use warnings;

my $teststr="\"abcd\"";

print "\nTestStr: $teststr\n";

`echo "$teststr" >> \/home\/folder\/samplequotes.txt`;

Output of the program above:

$ perl quotes1.pl

TestStr: "abcd"

$ cat samplequotes.txt

abcd

The problem i'm facing is that the double quotes in string are not getting into the text file.

Ideally, the contents of the samplequotes.txt file should have been:

"abcd"

Can anybody please tell me what would be the issue here ??

Upvotes: 0

Views: 5622

Answers (3)

Dave Cooper
Dave Cooper

Reputation: 10714

If you modify your input string to include the backslashes for your shell to interpret like this:

use strict;
use warnings;

my $teststr="\\\"abcd\\\"";

print "\nTestStr: $teststr\n";
`echo "$teststr" >> \/home\/folder\/samplequotes.txt`;

Then you will get the desired output to your samplequotes.txt file. The problem here was that your shell wasn't interpreting your input the way you thought it was.

Hope that helps!

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753595

Your problem is mixing Perl and shell; that's two similar but not identical sets of quoting conventions, and understanding the interaction between them is hard (since you need to understand both separately, as well as how they interact).

Perl expands:

`echo "$teststr" >> \/home\/folder\/samplequotes.txt`;

into:

echo ""abcd"" >> /home/folder/samplequotes.txt

and the shell treats the adjacent double quotes as empty, hence you get abcd in the file. If you don't want the shell interpreting the double quotes, write:

`echo '$teststr' >> /home/folder/samplequotes.txt`;

which the shell gets to see as:

echo '"abcd"'  >> /home/folder/samplequotes.txt

However, it is better not to run a shell simply to do the echo like that; it would be far more sensible to have Perl open the file and add the output to it and then close the file.

{
open my $fh, '>>', "/home/folder/samplequotes.txt" or die;
print $fh $teststr;
}

The braces limit the scope of the file handle to the four lines of code shown, and automatically close the file when the file handle goes out of scope.

The backslashes in the file name in your code are all rather pointless too. Perl removes them (AFAICT) so the shell doesn't get to see them.

Upvotes: 3

Miller
Miller

Reputation: 35198

Use perl's file processing to write to the file:

use strict;
use warnings;
use autodie;

my $teststr = '"abcd"';
my $file = '/home/folder/samplequotes.txt';

print "\nTestStr: $teststr\n";

open my $fh, '>>', $file;
print $fh $teststr;

Upvotes: 2

Related Questions