Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

How to pass a file to GetOpt

by Anonymous Monk
on Jul 10, 2012 at 21:33 UTC ( [id://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 -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 $_

Replies are listed 'Best First'.
Re: How to pass a file to GetOpt
by aaron_baugher (Curate) 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 line 11" Line 11 contains:

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

      Any ideas as to why?



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

        to see what you are actually trying to open.


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: # /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" ; }

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-16 19:41 GMT
Find Nodes?
    Voting Booth?

    No recent polls found