First, when you are debugging something like this, print the actual return code that Perl sees! You made an erroneous assumption that 256 would be -1! That is true in 8 bit 2's complement math. But that's not true here!

I personally would always prefer assigning a lexical var for the return code instead of using some "magic" Perl variable ($!). my $rc = system($cmd); #use $rc and perhaps $! also, but $rc is "the error code from system"

Ysth is completely correct - get the Perl process to change its directory, do not use a shell. That shell is a separate process.

But a main point here is that when things go "bad", print more stuff, like the return code from system(). Then you see that 256 != -1, etc.

#!usr/bin/perl -w use strict; my $cmd = "cd /cat/bat"; my $rc = system($cmd); print "rc = $rc\n"; #PRINTS: #The system cannot find the path specified. #rc = 256 $cmd = 'cd C:\temp'; $rc = system($cmd); print "rc = $rc\n"; #PRINTS: #rc = 0
Update: I would also add that most of the time an O/S error code is "0", zero upon success and non-zero when it fails. As with all things with software, this is not true always, but it is often true. So instead of checking for a comparison with -1 (or 256), better is usually is, if ($x !=0) for the error condition.

In reply to Re: system() command by Marshall
in thread system() command by Sun751

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.