1
#!/usr/bin/perl -w
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser);
use strict; 
print "Content-type: text/plain\n";
print "\n";

my $date = system('date');

print "Date :: $date";

The above code keeps producing the output of Date :: 0 instead of the current date.
I can't find any solution for this problem. Please help.

serenesat
  • 4,611
  • 10
  • 37
  • 53
BBbbBB
  • 87
  • 7
  • 2
    `system` returns the status code of the executed command, not the output. You could use the backticks instead. – dgw Nov 17 '15 at 09:42
  • 3
    or better you should use a perl function to get the date – Jens Nov 17 '15 at 09:43
  • And the title is misleading. This ist not a problem with CGI, it is a problem capturing the output of an external command. – dgw Nov 17 '15 at 09:44
  • Can you teach me how to use the backticks please. @dgw – BBbbBB Nov 17 '15 at 09:46
  • Searching within SO should give you enough input ... for example [here](http://stackoverflow.com/questions/799968/whats-the-difference-between-perls-backticks-system-and-exec) – dgw Nov 17 '15 at 09:58

2 Answers2

2

Instead of using system command, use backtick. system command doesn't return value in a variable. Change this line:

my $date = system('date');

to

my $date = `date`;

See this for more understanding about system and backtick: https://stackoverflow.com/a/800105/4248931

Community
  • 1
  • 1
serenesat
  • 4,611
  • 10
  • 37
  • 53
1

The return value of the system command is the return value of the call. For a successful call this will be 0. If you want to capture the output of a command use backticks or IPC. Look at this answer: Capture the output of Perl system()

my $date = `date`;

print "Date :: $date";

But better would be to use DateTime.

Community
  • 1
  • 1
bolav
  • 6,938
  • 2
  • 18
  • 42
  • 3
    DateTime is not in the Perl core. To get a textual representation of the date, it's enough to simply call `localtime`. – simbabque Nov 17 '15 at 10:01