Execute command and return error

Posted on 2007-07-22
Last Modified: 2010-03-05

How do I let perl execute a command and return a possible error?

RM file.txt - in shell this would return an error: No such file.
Perl however won't give that error... Is it possible to let perl display that error?

See, I want to start a program using perl, but now I have no idea whether it started or not.
And if It didn't, then i want to know why (error).

print "Content-type:text/html\n\n";
$res = `rm file.txt`;
print $res;

Thank you.
Question by:TonyJix
    LVL 48

    Accepted Solution


    To get the error, you need to capture stderr

    $res = `rm file.txt 2>&1`;

    However, usual way of running external commands where you don't need to capture the output is

    system "rm file.txt" and die "rm failed $!\n";
    LVL 39

    Expert Comment

    If you want to remove a file in perl, you should use the built-in command unlink, rather than a shell command.  It will return the number of files removed, and set $! to the error, if any:

    unlink 'file.txt' or die "Could not remove file.txt: $!\n";

    Author Comment

    Alright... the remove thing was only an example though, but it's appreciated.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    On Microsoft Windows, if  when you click or type the name of a .pl file, you get an error "is not recognized as an internal or external command, operable program or batch file", then this means you do not have the .pl file extension associated with …
    Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
    Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
    To add imagery to an HTML email signature, you have two options available to you. You can either add a logo/image by embedding it directly into the signature or hosting it externally and linking to it. The vast majority of email clients display l…

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now