Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

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 -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
Node Status?
node history
Node Type: perlquestion [id://980952]
Approved by tobyink
Corion is not sure if this is serious
[LanX]: I've already outlined. you might want to add a link
[LanX]: oopp ssorry ...
[LanX]: ... thought it's a root post

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (11)
As of 2017-01-17 18:16 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (158 votes). Check out past polls.