Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

How to pass a file to GetOpt

by Anonymous Monk
on Jul 10, 2012 at 21:33 UTC ( #980952=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a program where I need to pass a filename (and location) to the program. How can I do this? I have read the GetOpt doc so please don't point me there. My command line is as follows:

perl myprogram.pl -input C:\inputfilelocation -output C:\outputfileloc +ation

My GetOptions look like this:

GetOptions('input=s' => \$input,'output=s' => \$output);

Basically I need to figure out how to access that file in a while loop that I have which iterates over the lines in the file and puts each into $_

Comment on How to pass a file to GetOpt
Select or Download Code
Re: How to pass a file to GetOpt
by onelesd (Pilgrim) on Jul 10, 2012 at 21:58 UTC

    Are you using linux?

    perl -e 'while (<>) {chomp;print "=>$_<\n";}' < infile > outfile

      Sorry, forgot to clarify, I am using Windows command prompt. I am looking for how to do this in the code. For example:

      while ($input){

      Only that doesn't work.

        # usage: # script.pl /path/to/infile /path/to/outfile die "infile not defined\n" if (! defined $ARGV[0]) ; die "outfile not defined\n" if (! defined $ARGV[1]) ; open my $infile, "< $ARGV[0]" or die "can't read $ARGV[0]\n" ; open my $outfile, "> $ARGV[1]" or die "can't write $ARGV[1]\n" ; while (<$infile>) { chomp ; print $outfile "=>$_<\n" ; }

Re: How to pass a file to GetOpt
by aaron_baugher (Deacon) on Jul 10, 2012 at 22:21 UTC

    Your GetOptions call puts the pathnames of the files in the variables $input and $output. So now you just need to open those files and do stuff with them:

    open my $in, '<', $input or die $!; open my $out, '>', $output or die $!; while(<$in>){ # do stuff to $_ print $out $_; # or whatever output you come up with }

    Aaron B.
    Available for small or large Perl jobs; see my home node.

      Aaron, I am getting an error: "No such file or directory at 5MinInterval2.pl line 11" Line 11 contains:

      open my $in, '<', $input or die $!;

      Any ideas as to why?

        Hi,

        Change

        open my $in, '<', $input or die $!; to open my $in, '<', $input or die "$! - [$input]";

        to see what you are actually trying to open.

        J.C.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://980952]
Approved by tobyink
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (10)
As of 2014-08-29 13:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (280 votes), past polls