PDA

View Full Version : Checking Text File Input Problem


welshhuw
03-16-2009, 09:16 PM
Hi,

In my program I need to check if an argument (text file) has been provided, and if not, I need the program to ask the user for a filename via the keyboard.
I have written the code below and it almost works!

The problem I am getting is that if an argument HAS been provided, the if clause works correctly. (And asks the user for input via STDIN)

But, if an argument HAS NOT been provided, the if clause prints to the screen and runs the else clause. (Without letting the user enter data)

Maybe if you copy and paste this code you can see for yourself what i mean.


Any help would be greatly appreciated?
Thanks in advance.


if($#ARGV== -1)
{
print("Enter a Filename Please: ");
$filename = <STDIN>;
chomp($filename);
}
else
{
$filename = $ARGV[0];
}

oesxyl
03-16-2009, 09:23 PM
my $filename = shift @ARGV;
if($filename){
$filename = <STDIN>;
chomp($filename);
}


bst regards

welshhuw
03-16-2009, 09:47 PM
Thx for your help oesxyl, but it still giving me the same result as my coding??
i added an else clause and it works fine with that. but if a file is added then the if clause still runs?? and the else clause print statements gets printed to screen along with the first line of text from the textfile??

oesxyl
03-16-2009, 09:54 PM
Thx for your help oesxyl, but it still giving me the same result as my coding??
i added an else clause and it works fine with that. but if a file is added then the if clause still runs?? and the else clause print statements gets printed to screen along with the first line of text from the textfile??
sorry, is my fault, :)
it's obvious wrong because if you pass a argument will ask again for another. This is the correct code:

my $filename = shift @ARGV;
if(!defined($filename)){
$filename = <STDIN>;
chomp($filename);
}


best regards

KevinADC
03-16-2009, 10:04 PM
perl has the "unless" conditional that can be used in place of negation:

my $filename = shift @ARGV;
unless($filename){
$filename = <STDIN>;
chomp($filename);
}


I like to use it but there is nothing wrong with the other way.

oesxyl
03-16-2009, 11:51 PM
perl has the "unless" conditional that can be used in place of negation:

my $filename = shift @ARGV;
unless($filename){
$filename = <STDIN>;
chomp($filename);
}


I like to use it but there is nothing wrong with the other way.
yes, is more clear with unless. :)
Anyway the proper way would be to use a while and exit or do something else if user don't want to provide a filename.

best regards

welshhuw
03-17-2009, 06:09 PM
Sorted thanks guys!