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.
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)- A10% (4)
- B83% (33)
- C5% (2)
- D3% (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.
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.
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.
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.
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
Community Discussion
No community discussion yet for this question.