473,320 Members | 1,695 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

trapping file i/o error


In most perl examples, it used this method to trap error:

open(INFILE, $fname) or die "Unable to open $fname";
process_file();
close(INFILE)
other_codes();

Now that if I don't want to die after the open so as to run
other_codes()? Could I test the value of file handle INFILE like what I
did with C?

fhandle=fopen(fname,"r")
if (fhandle > 0) {
process_file();
fclose(fhandle)
}
else
show_error()
other_codes();

--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 5:00pm up 2 days 18:54 load average: 1.00 1.00 1.00
Jul 19 '05 #1
15 6007
toylet wrote:

In most perl examples, it used this method to trap error:

open(INFILE, $fname) or die "Unable to open $fname";
process_file();
close(INFILE)
other_codes();

Now that if I don't want to die after the open so as to run
other_codes()? Could I test the value of file handle INFILE like what I
did with C?

fhandle=fopen(fname,"r")
if (fhandle > 0) {
process_file();
fclose(fhandle)
}
else
show_error()
other_codes();

Try something like this:
if ( -e $fname && -r $fname) {
open(INFILE, $fname) or show_error();
}
else {
die "Unable to open $fname";
}

The "-e" tests if the file exists and the "-r" tests if the file is
readable. If you want to see if it is writable use "-w". By testing
for the existence of the file and if you can read from or write to the
file first you can handle those situations gracefully and not have to
capture the error condition.

There is nothing special about the "or die". The "or" is just a logical
operator. Perl uses a short cut optimization of boolean statements.
the open statement returns a 1 if it suceeds and undefined if it fails.
So when the open statement succeeds it returns 1 and evaluating "1 or
anything" will alwayse be true so it will not do the "anything" on the
other hand of the open fails the returned undefined is treated as false
so the second part of the or needs to be evaluated so it could be any
statement or block of statement you want. Do not expect to get anything
of use out of the fhandle.

If you are going to continue writing scripts in perl I would suggest
getting a good book on it. My preferences are either from O'Reilly or
Wrox (if you can find them).

--
Thanks
Charles LaCour
Jul 19 '05 #2
Try something like this:
if ( -e $fname && -r $fname) {
open(INFILE, $fname) or show_error();
}
else {
die "Unable to open $fname";
}
statement or block of statement you want. Do not expect to get anything
of use out of the fhandle.
Too bad. I thought checking he file handle is the best appraoch. in
fact, many languages do that, like SQLCONNECT() in Foxpro, fopen() in
C/Clipper/Foxpro, ... It would be quite troublesome to work around that.
If you are going to continue writing scripts in perl I would suggest
getting a good book on it. My preferences are either from O'Reilly or
Wrox (if you can find them).


There are many websites hosting Perl books online. I use google.com to
find them. Thanks for the advice. What I really need is a job that
demands the use of perl, which is rather scarse in my city. Most of them
uses M$ tools.
--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 4:08pm up 5:41 1 user 1.03 1.01
Jul 19 '05 #3
toylet wrote:
In most perl examples, it used this method to trap error:

open(INFILE, $fname) or die "Unable to open $fname";
process_file();
close(INFILE)
other_codes();

Now that if I don't want to die after the open so as to run
other_codes()? Could I test the value of file handle INFILE like what I
did with C?


In perl, open() does not return a file handle but it does return
a true/false value you can test.

if (open(INFILE, $fname)) {
process_file(INFILE);
close(INFILE);
} else {
warn "Unable to read $fname: $!\n";
}
other_codes();

Be sure to include $! in the error message; it has strerror(errno).
-Joe
Jul 19 '05 #4
> In perl, open() does not return a file handle but it does return
a true/false value you can test.
if (open(INFILE, $fname)) {
Be sure to include $! in the error message; it has strerror(errno).
-Joe


that's what I should be going after. thanks.

--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 7:46pm up 9:19 1 user 1.00 0.94
Jul 19 '05 #5
> Be sure to include $! in the error message; it has strerror(errno).

"$!" is a text message. can I get the errorno?
is it "$?" as in bash?

--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 7:48pm up 9:21 1 user 1.00 0.94
Jul 19 '05 #6
toylet wrote:
Be sure to include $! in the error message; it has strerror(errno).

"$!" is a text message. can I get the errorno?
is it "$?" as in bash?


$! = 28; # ENOSPC = 'No space left on device'
print "As a string, the last error was '$!'\n";
print "As a number, errno was ", $!+0, "\n";

That is, $! is magic. See also 'perldoc perlvar'.
-Joe
Jul 19 '05 #7
Thank you. Seems that perl requires the programms the know about context.
print "As a string, the last error was '$!'\n";
print "As a number, errno was ", $!+0, "\n";


--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 3:28pm up 15:48 1 user 1.02 1.00
Jul 19 '05 #8
bob
toylet wrote:
Thank you. Seems that perl requires the programms the know about context.
print "As a string, the last error was '$!'\n";
print "As a number, errno was ", $!+0, "\n";



Yes. but once you *do* know about it, it can be very convenient.
Jul 19 '05 #9
hmm... how do you force a variable into a certain context (could I also
call it "type casting")?

for integer, $i+0 or (int)$i.
for string, $i+""? or is it (string)$i?
for array
for hash
Yes. but once you *do* know about it, it can be very convenient.


--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 1:10pm up 2:19 1 user 1.41 1.33
Jul 19 '05 #10

toylet <toylet_at_mail.hongkong.com> wrote:
hmm... how do you force a variable into a certain context (could I also
call it "type casting")?
You almost never need to. About the time string/number matters is with
magic values like $!; other than that, scalar context can be forced with
scalar() or unary + and list context with parentheses ().
for integer, $i+0 or (int)$i.
yes no, though int($i) will give you int rather than
float
for string, $i+""? or is it (string)$i?
$i.'' or "$i" no
for array
for hash


eh what? Please explain what you expect, e.g., (hash)$i to achieve?

Ben

--
And if you wanna make sense / Whatcha looking at me for? (Fiona Apple)
* be*@morrow.me.uk *
Jul 19 '05 #11
>> for array
for hash


eh what? Please explain what you expect, e.g., (hash)$i to achieve?


Just asking for a general method of forcing context.

--
.~. Might, Courage, Vision. In Linux We Trust.
/ v \ http://www.linux-sxs.org
/( _ )\ Linux 2.4.22-xfs
^ ^ 3:24pm up 4:33 1 user 1.79 1.45
Jul 19 '05 #12
Ben Morrow <us****@morrow.me.uk> wrote in comp.lang.perl.misc:

toylet <toylet_at_mail.hongkong.com> wrote:
hmm... how do you force a variable into a certain context (could I also
call it "type casting")?
You almost never need to. About the time string/number matters is with
magic values like $!; other than that, scalar context can be forced with
scalar() or unary + and list context with parentheses ().


Parentheses only provide list context on the left side of an assignment
(anywhere else?). Watch this:

sub wanta { print wantarray ? "array\n" : "scalar\n" }

$x = wanta;
( $x) = wanta;
$x = ( wanta);
( $x) = ( wanta);

The parentheses on the right side don't seem to do anything.

I can't meaningfully say much about the difference between unary +
and scalar(), except that there is one. Vaguely, "+" can change parsing,
scalar() can't.

[...]
And if you wanna make sense / Whatcha looking at me for? (Fiona Apple)


Can't say I understand that sig of your's, but I like it :)

Anno
Jul 19 '05 #13
Ben Morrow <us****@morrow.me.uk> wrote in comp.lang.perl.misc:

toylet <toylet_at_mail.hongkong.com> wrote:
hmm... how do you force a variable into a certain context (could I also
call it "type casting")?
You almost never need to. About the time string/number matters is with
magic values like $!; other than that, scalar context can be forced with
scalar() or unary + and list context with parentheses ().


Parentheses only provide list context on the left side of an assignment
(anywhere else?). Watch this:

sub wanta { print wantarray ? "array\n" : "scalar\n" }

$x = wanta;
( $x) = wanta;
$x = ( wanta);
( $x) = ( wanta);

The parentheses on the right side don't seem to do anything.

I can't meaningfully say much about the difference between unary +
and scalar(), except that there is one. Vaguely, "+" can change parsing,
scalar() can't.

[...]
And if you wanna make sense / Whatcha looking at me for? (Fiona Apple)


Can't say I understand that sig of your's, but I like it :)

Anno

Jul 19 '05 #14
toylet wrote:
for array
for hash

eh what? Please explain what you expect, e.g., (hash)$i to achieve?


Just asking for a general method of forcing context.


($a,$b) = foo(); # List context
@array = foo(); # List context
%hash = foo(); # List context
foo(); # Null context
$var = foo(); # Scalar context
$var = +foo(); # Numeric scalar context
$var = foo().""; # String scalar context
if (foo()) {}; # Boolean scalar context

-Joe
Jul 19 '05 #15
[ F'up set to clpm;
comp.lang.perl doesn't exist ]

Also sprach Joe Smith:
toylet wrote:

Just asking for a general method of forcing context.


($a,$b) = foo(); # List context
@array = foo(); # List context
%hash = foo(); # List context
foo(); # Null context
$var = foo(); # Scalar context
$var = +foo(); # Numeric scalar context


Nope. This does not force numeric context. This does:

$var = foo() + 0;

Or this:

$var = foo() * 1;

Any numeric operator in conjunction with the neutral element with
respect to the used operator can be used to enforce numeric context.

Tassilo
--
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus}) !JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexi ixesixeseg;y~\n~~dddd;eval
Jul 19 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Nathan Bloomfield | last post by:
Hi there, I am having difficulty with a piece of code which would work wonders for my application if only the error trapping worked properly. Basically, it works as follows: - adds records...
21
by: Neil | last post by:
Is there a way to trap an error generated in another app that is controlled via automation? I have an Access 2000 app that opens Word 2000 and proceeds to open a series of documents and, in each...
3
by: windandwaves | last post by:
Hi Gurus Does anyone know how I set the error trapping to option 2 in visual basic. I know that you can go to tools, options and then choose on unhandled errors only, but is there a VB command...
13
by: Thelma Lubkin | last post by:
I use code extensively; I probably overuse it. But I've been using error trapping very sparingly, and now I've been trapped by that. A form that works for me on the system I'm using, apparently...
4
by: Bill | last post by:
Despite our best efforts occasionally in an aspx file, something like <%=x%> where x is not defined sqeaks by and I get the ugly asp error message. I want to be able to identify this particular...
6
by: SMG | last post by:
Hi , Sory for incomplete message in last post here is the actual problem.. I am using following code in web.confiig for trapping all the error through out my site.. <customErrors mode="On"...
2
by: Fred Nelson | last post by:
I'm devloping a VB.NET web application and I'm having a problem with trapping errors and logging the cause of them. When an unexpected error occurs I want to write it to a file - or e-mail it to...
6
by: sara | last post by:
I have a procedure to automate bringing several Excel files into our Access tables, on a daily basis. The problem is that if the user has a problem, and tries to run the import again (maybe 3...
2
by: Captain Nemo | last post by:
I'm still using Office 2000 myself, but some of my clients have Office 2003. I've recently added a piece of code to create an instance of Word, open a document, fill in the blanks and become...
9
by: 47computers | last post by:
Pretty new to PHP, I recently started learning about error trapping. As of right now, I include the following into a page in my website: -------BEGIN PASTE-------- error_reporting(E_ERROR |...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.