Using backticks

Single quotes can be used to specify a literal string which can be printed, assigned to a variable, et cetera. Double quotes perform interpolation of variables and certain escape sequences such as \n to create a string which can also be printed, assigned, etc.

A new set of quotes, called backticks, can be used to interpolate variables then run the resultant string as a shell command. The output of that command can then be printed, assigned, and so forth.

Backticks are the backwards-apostrophe character (` which appears below the tilde (~), next to the number 1 on most keyboards.

Just as the q() and qq() functions can be used to emulate single and double quotes and save you from having to escape quotemarks that appear within a string, the equivalent function qx() can be used to emulate backticks.

Backticks and the qx() function are discussed in the Camel on pages 52 and 41 respectively or in perldoc perlop.

Exercises

  1. Modify your earlier finger program to use backticks instead of system() (Answer: exercises/answers/backtickfinger.pl)

  2. Change it to use qx() instead (Answer: exercises/answers/qxfinger.pl)

  3. The Unix command whoami gives your username. Since most shells support backticks, you can type finger `whoami` to finger yourself. Use shell backticks inside your qx() statement to do this from within your Perl program. (Answer: exercises/answers/qxfinger2.pl)