Re: Question about warn statement
by dreadpiratepeter (Priest) on Aug 22, 2003 at 15:52 UTC
|
unless (open(FILE,">temp")) {
warn "error";
$x=1;
}
-pete
"Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere." | [reply] [d/l] |
|
|
unless (open my $fh, '<', 'file') {
# . . .
}
In that code, $fh is lexical to the unless block. That probably isn't what you want because you only enter the block if the open fails. This pitfall may be more likely to come up when changing existing code than when writing new code altogether.
You can get around it by declaring $fh prior to the unless but, now anyway, I prefer to avoid it by using
open my $fh, '<', 'file' or do {
# . . .
};
instead. That also puts the emphasis back on the open statement itself.
-sauoq
"My two cents aren't worth a dime.";
| [reply] [d/l] [select] |
|
|
I know 'unless' is the right *perl* way to do that, but I've never quite gotten used to using 'unless'. I prefer to use 'if not' in place of 'unless' - it just makes more sense to me:
if (not open(FILE, ">temp")) {
warn "error";
$x = 1;
}
HTH. | [reply] [d/l] |
Re: Question about warn statement
by mattriff (Chaplain) on Aug 22, 2003 at 15:54 UTC
|
open(FILE,">temp") or warn "error message" and $x = 1;
Or, if you don't feel a need to use one line:
open(FILE,">temp") or $x = 1;
$x and warn "error message";
Or, do what dreadpiratepeter said to, if you want to
be absolutely clear. :)
- Matt Riffle
Sr. Systems Programmer, pair Networks, Inc.
(although, I speak only for myself; code is untested unless otherwise stated) | [reply] [d/l] [select] |
Re: Question about warn statement
by roju (Friar) on Aug 22, 2003 at 16:52 UTC
|
In the spirit of TMTOWTDI, and because of my love for the comma operator,
open (FILE,">temp") or $x=1, warn "error message" | [reply] [d/l] |
Re: Question about warn statement
by CombatSquirrel (Hermit) on Aug 22, 2003 at 16:03 UTC
|
Or do a do (and be careful about the scope):
open (FILE, '>', "temp") or do { warn "error message"; $x=1 };
| [reply] [d/l] [select] |
Re: Question about warn statement
by vek (Prior) on Aug 22, 2003 at 16:31 UTC
|
my $x;
open (FILE, ">temp") || do {
warn "error message";
$x = 1;
};
--
vek
-- | [reply] [d/l] |
|
|
my $x;
open (FILE, ">temp") || do {
warn "error message";
$x = 1;
}
print "\$x is $x";
dave
| [reply] [d/l] [select] |
|
|
my $x;
open (FILE, ">temp") || do {
warn "error message";
$x = 1;
};
if ($x) {
# so something
}
--
vek
-- | [reply] [d/l] [select] |
|
|
| [reply] |
Re: Question about warn statement
by tcf22 (Priest) on Aug 22, 2003 at 16:05 UTC
|
open(FILE,">temp") || (warn "error message" and ($x = 1));
Update: Changed code to avoid wierd issue | [reply] [d/l] |
|
|
open(FILE,"<temp") || (($x = 1) && warn "error message1: $x");
open(FILE,"<temp") || (($x = 0) && warn "error message2: $x");
__END__
error message1: 1 at test-a.pl line 1.
| [reply] [d/l] |