0

I've been trying to figure out how to run this example for a while now and I'm still stuck on how to print the date. Below is the example I'm working on.

(The Script for Unix/Linux)
# Backquotes and command substitution
1   print "The date is ", 'date';      # Windows users: 'date /T'
2   print "The date is 'date'", ".\n"; # Backquotes treated literally
3   $directory='pwd';                  # Windows users: 'cd'
4   print "\nThe current directory is $directory.";

(Output)
1   The date is Mon Jun 25 17:27:49 PDT 2007.
2   The date is 'date'.
4   The current directory is /home/jody/ellie/perl.

This is my work and output.

print "The date is ", 'date /T';
print "The date is 'date'", ".\n"; 
$directory='cd';
print "\nThe current directory is $directory.";  

(Output)
The date is date /TThe date is 'date'.
The current directory is cd. 

Any help with this is greatly appreciated. Thanks.

2 Answers 2

2

You already have a good explanation of what you're doing wrong (using single quotes instead of backticks or qx(...)) but it's probably worth pointing out that you don't need to call external programs in either of the two cases in your examples.

To get the current date, just call localtime in scalar context.

print scalar localtime;

For more complex date and time handling see Time::Piece and DateTime.

To get the current directory, use Cwd.

use Cwd;

print getcwd;

Not running unnecessary external programs is a good idea for two reasons. Firstly it makes your code more portable, and secondly it's more efficient (external programs are run in a new shell environment - and starting one of those is a relatively expensive operation).

Sign up to request clarification or add additional context in comments.

Comments

1

You have to use backticks instead of single quotes:

print "The date is ", `date /T`;
print "The date is ", `date`, ".\n"; 
$directory=`cd`;
print "\nThe current directory is $directory.";  

2 Comments

Because a similar issue discouraged me from programming when I first tried it as a kid, I'll add this advice: the backtick on a US keyboard is the button below ESC. On other layouts, it might be harder to find. On e.g. a German one, it's the button left of backspace, which you have to press while holding shift, and then pressing space as it's intended as a diacritical mark called grave accent that can also be put on a letter, like è. If that doesn't help, copy it from here: `
or use qx() which is easier to type and may even look nicer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.