nerdexam
IBM

000-221 · Question #14

Within a Perl script, how can the output of the hostname command be assigned to a variable called myHostname?

The correct answer is B. chop($myHostname=%hostname -s 2>/dev/nuir). In Perl, the backtick operator executes a shell command and returns its stdout as a string, and chop() strips the trailing newline that command substitution appends.

System Management

Question

Within a Perl script, how can the output of the hostname command be assigned to a variable called myHostname?

Options

  • AchopfmyHostname-'hostname -s 2>/dev/null")
  • Bchop($myHostname=%hostname -s 2>/dev/nuir);
  • C$myHostname=7usr/bin/hostname".
  • Dchomp(@myHostname-hostname -s 2>/dev/null');

How the community answered

(40 responses)
  • A
    10% (4)
  • B
    83% (33)
  • C
    5% (2)
  • D
    3% (1)

Why each option

In Perl, the backtick operator executes a shell command and returns its stdout as a string, and chop() strips the trailing newline that command substitution appends.

AchopfmyHostname-'hostname -s 2>/dev/null")

Perl single-quoted strings are fully literal - no interpolation or command execution occurs - so enclosing the hostname command in single quotes assigns the raw text string rather than running it.

Bchop($myHostname=%hostname -s 2>/dev/nuir);Correct

Perl's backtick operator (the delimiters around 'hostname -s 2>/dev/null' in this answer) executes the shell command in a subshell and captures its standard output as a string assigned to the scalar $myHostname. Wrapping the assignment in chop() removes the trailing newline character appended by the shell, leaving a clean hostname value stored in the correct scalar variable.

C$myHostname=7usr/bin/hostname".

Assigning '/usr/bin/hostname' as a quoted string stores only the path as a literal scalar value and never executes the command or captures any output.

Dchomp(@myHostname-hostname -s 2>/dev/null');

Using @myHostname declares an array variable rather than the scalar $myHostname requested by the question, producing the wrong variable type and name.

Concept tested: Perl backtick command substitution and output capture

Source: https://perldoc.perl.org/perlop#Quote-and-Quote-like-Operators

Topics

#Perl scripting#command output capture#variable assignment#shell integration

Community Discussion

No community discussion yet for this question.

Full 000-221 Practice