snoop
snoop

Reputation: 171

Perl's backticks not working on Windows but works fine on Linux

I have simple script perlSample.pl which print date and time only:

my $cmd = 'perl -e \'my $datestring = localtime( time );print $datestring\'';
my $line = `$cmd 2>&1`;
my $ret = $?;
print $line;

This script is working fine in Ubuntu but when I run on Windows Xp its give me error:

Can't find string terminator "'" anywhere before EOF at -e line 1.

On Windows XP I have the ActivePerl (v5.20.1) and Ubuntu (v5.20.1) same version. Where is the mistake?

Upvotes: 0

Views: 497

Answers (4)

Brad Gilbert
Brad Gilbert

Reputation: 34130

You should use a module which handles quoting the arguments for you.

use IPC::Cmd qw' run ';

# prints to STDERR as an example
my @cmd = ('perl', '-e', 'print STDERR scalar localtime');

my $lines; # the output buffer

# buffer gets both STDOUT and STDERR
run( command => \@cmd, buffer => \$lines );

print $lines, "\n";

This has the benefit that it comes with Perl, and it quotes the command appropriately for your platform.


The way you would do this in Perl6 is a bit different, as it doesn't come with IPC::Cmd, instead you would most likely use the built-in Proc::Async module.

#! /usr/bin/env perl6

use v6; # provides a good error message on Perl 5.8 and newer

my $process = Proc::Async.new('perl6', '-e', '$*ERR.say: DateTime.now');

my @parts;

$process.stdout.tap: { @parts.push('STDOUT' => $_) unless /^ \s* $/ } #;
$process.stderr.tap( { @parts.push('STDERR' => $_) unless /^ \s* $/ } );
# you can "tap" the stderr and stdout Supplys multiple times if you want

{
  my $promise = $process.start;
  # can do other things here, while we wait

  # halt this program until the other one finishes
  await $promise;
}

.say for @parts;
STDERR => 2015-01-26T10:05:42-0600

As you can see using the Proc::Async module requires a bit more code, but it makes up for it by being more flexible.

Upvotes: 0

my $cmd = 'perl -e "my $datestring = localtime( time );print $datestring"'; my $line =$cmd 2>&1; my $ret = $?; print "$line $ret";

single quotes will not work in windows command line you have to use the double quotes to get the same result in windows

Upvotes: 0

user4322779
user4322779

Reputation:

I found that my $cmd = "perl -e print(localtime(time))"; works fine on Windows 7 at least - don't have WindowsXP any more.

That enables externalizing the command for use in Windows and Linux.

Upvotes: 0

mpapec
mpapec

Reputation: 50667

What you want to achieve can be much simpler and portable without the need of calling external instance of perl interpreter,

my $line = localtime( time );
print $line;

but if you for some reason insist on it, you have to use double quotes under win32, perl -e ".."

my $cmd = 'perl -e "my $datestring = localtime( time );print $datestring"';
my $line = `$cmd 2>&1`;
my $ret = $?;
print $line;

Upvotes: 1

Related Questions