By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,541 Members | 1,476 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,541 IT Pros & Developers. It's quick & easy.

Opening a file and outputing the contents

P: 67
Alright I can't seem to get this to actually read from the file but I believe I'm doing it correctly, but obviouslly I'm not.

Expand|Select|Wrap|Line Numbers
  1. my $fileName = "guessingGame.csv";
  3. sub load()
  4. {    
  5.     open (MYFILE, $fileName) || die(print "Could not open file!");
  6.     while (<MYFILE>) 
  7.     {
  8.         chomp;
  9.         print "$_\n";
  10.     }
  11.     close (MYFILE); 
  12. }
Feb 23 '09 #1
Share this Question
Share on Google+
4 Replies

Expert 100+
P: 410
There is nothing wrong in the script. It should work once you call the subroutine:
Expand|Select|Wrap|Line Numbers
  1. &load();   
Feb 23 '09 #2

P: 67
If I'm using windows is their a difference?
Feb 23 '09 #3

Expert 2.5K+
P: 4,059
No there is no difference. Your open() function is inside a subroutine (well really a prototype in your case) so you have to call the subroutine to tell perl to run the subroutine.

Expand|Select|Wrap|Line Numbers
  1. my $fileName = "guessingGame.csv";
  2. load();#<-- now perl will run the subroutine
  5. sub load {    
  6.     open (MYFILE, $fileName) || die(print "Could not open file!");
  7.     while (<MYFILE>)  {
  8.         chomp;
  9.         print "$_\n";
  10.     }
  11.     close (MYFILE); 
  12. }
Don't use parentheses after subroutine names:

sub load() {

That is a called a prototype and you certainbly have no reason to use them and probably never will so just drop the parentheses from now on:

sub load {

You should also pass arguments to your subroutines and pass data back although in this case there is no data to pass back really since you are only using the subroutine to open a file, print its contents and nothing else. Not really a good use of a subroutine.
Feb 23 '09 #4

Expert Mod 2.5K+
P: 3,503
There shouldn't be a difference for the code you have shown us. What happened when you ran the subroutine as Nithinpes suggested?

Also, the only thing that I see is in your die() statement. If you look at the documentation, you don't need the print inside of it as whatever is in the quotes gets printed by the die function already. You just put in the message you want to have output if the open fails.


Feb 23 '09 #5

Post your reply

Sign in to post your reply or Sign up for a free account.