Need return code from perl -e command

P

Paul Porcelli

Hi folks,
I have a perl one-liner embedded in a ksh script.

perl -pi.bak -e "s/val/otherval/" inputfile

I'd like to check the return code to know
if the substitution was successful.

If I type:
# perl -pi.bak -e "s/val/otherval/" inputfile
Can't open inputfile: No such file or directory
# echo $?
0

If the file is found i still get a return code of 0
# perl -pi.bak -e "s/val/otherval/" realfile
# echo $?
0

Any ideas ?

Many thanks
Paul
 
P

Paul Porcelli

Hi Alex,
thanks a lot for the reply.
That command doesn't seem to work for me.
It's partially OK if the string is found
i.e.
# perl -pi.bak -e '$c+=s/test/newval/; END {exit !$c;}' /tmp/testfile
# more /tmp/testfile
0newval
N.B. The return code 0 has been pasted into the file.
# echo $?
0

If there are no substitutions:
# perl -ne '$c+=s/echo/newval/; END {exit !$c;}' /tmp/testfile
Callback called exit, <> chunk 1.
END failed--cleanup aborted, <> chunk 1.
# echo $?
255

Any ideas how to avoid putting the return code in the file ?

Thanks again
Paul
 
C

Carlos J. G. Duarte

Paul said:
Hi folks,
I have a perl one-liner embedded in a ksh script.

perl -pi.bak -e "s/val/otherval/" inputfile

I'd like to check the return code to know
if the substitution was successful.

Hi, I was replying to this the other day, when my laptop crashed! Let's
try take two now...

Perl returns the result of the last evaluated expression. perl -p is
equivalent to include all code between a while (<>) {}, so if the file
exists it enters the while loop, does it's work, and returns when <>
returns undef. Therefor here the last evaluated expression is <> that
have returned undef (or something) -- perl exits 0. When the file does
not exist, the <> implicitly returns undef again (open on a non existent
file).

To actually have a different return code based on taking or not some
action, one must consider that case in the script. Two examples:

#1 exit via the $! perl var
perl -i -p -e '$!=0; s/foo/bar/ END { return !!$! }' files

#2 take some var to control the number of processed lines
perl -i -p -e '$c++; s/foo/bar/ END { return !$c }' files

Both has some problems, for instance, the first will return false if the
lsat file does not exists (independently of the first and second, etc);
the later will return false if no file has lines.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top