Keenan, Greg John (Greg)** CTR ** wrote:
> Hi,
> 
> Can someone explain the difference between backticks and system when
> evaluated in this if statement:
>

The difference really isn't specific to this context, it is the inherent
difference between the two that is affecting the outcome.

perldoc -f system
perldoc perlop

For the details. The main difference is that 'system' runs the command
and returns the exit value, which is (usually) 0 for success and
non-zero for failure. Perl is successfully shelling out to /bin/date and
it successfully runs so it returns 0 so the if evaluates to false.
The fact that you see the date printed to the terminal in this case is
merely a side effect of the fact that Perl and the subshell share the
same standard out filehandle and it happens to be your terminal screen.
Backticks on the other hand return whatever output was provided by the
program being run, so in this case the date string is returned, which
evaluates to true, so even though the program ran successfully the if
evaluates and you get the error message. In the first case your if
blocks should be reversed, in the second case you should capture the
output to a scalar or array and if you want to check the exit status
then you would need to look in $?. The docs for 'system' explain it more.

> 
> sub getDate {
>  print "start date\n";
>  if ( system("/bin/date") ) {
>    print "can't get date\n";
>    exit(2);
>  }
>  print "finish date\n";
> }
> 
> Returns the following:
> 
> start date
> Thu Jul 28 12:13:59 EST 2005
> finish date
> 
> 
> 
> While this:
> 
> sub getDate {
>  print "start date\n";
>  if ( `/bin/date` ) {
>    print "can't get date\n";
>    exit(2);
>  }
>  print "finish date\n";
> }
> 
> Returns this:
> 
> start date
> can't get date
> 

Hopefully this is an example, don't use either to get the date. Perl has
built-in functions for that. Shelling out with either of the above
methods is a last resort when there is no other way to accomplish the
same task from within Perl.

http://danconia.org

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to