Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

Open file -- make it nicer ?

Hi *

I want my script (Perl on Windows 32b) to receive 2 command line parameters e.g test.pl <filename> <style>
filename is textfile and style is one-digit character.

Here is how I check and open for file :

if (! @ARGV) {
print "Warning : Please provide input file.";
}    

# Open a file
my $f;
open(FH, $f = shift @ARGV) || die "Error -- cannot open : $f!";

# Read style ...

When I run this script it always show the following message if the input file does not exist.

C:\Perl\eg>perl -w test.pl rte 1
Error -- cannot open : rte! at test.pl line 398

How can I avoid the message after (!) ? It means I do not want to see "at test.pl line 398".

Thanks for idea
-iman
0
asampadeh
Asked:
asampadeh
1 Solution
 
particleCommented:
don't assign in the open statement.

try something like:

# Open a file
my $f= shift @ARGV;
open(FH, $f) || die "Error -- cannot open : $f!";
 



even better, deal with your arguments in one place. how about:

2 > @ARGV and die "Usage: $0 filename style\n";
my( $infile, $style )= @ARGV;

open FH, '<', $infile
  or die "cannot open file: $!";

## ...
0
 
wilcoxonCommented:
To avoid getting the "at test.pl line 398", you need to put a newline into your die.  The following should work:

open(FH, $f = shift @ARGV) || die "Error -- cannot open : $f!\n";
0
 
ItatsumakiCommented:
The guys above are right, so this is a bit of an aside.  I'm a big supporter of explicitly getting your @ARGV values into locals before testing them:

my $infile = $ARGV[0];
my $style  = $ARGV[1];

if (!$infile) {
     print "Life sucks: no infile!\n";
     exit();
     }
if (!$style) {
     # handle this case here
     }

I would also suggest that you get into the habit of using the file test operators -f (to check if it's a file) and -T (to check if it's a text file).

if (-T $infile) { #do stuff }
0
 
asampadehAuthor Commented:
It is complete and I learn new thing with additional file test. Direct open(FH,$infile) is the culprit at least in my activeperl script.

Thanks all.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now