Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

First time using Args

by mmusser (Initiate)
on May 03, 2012 at 17:02 UTC ( [id://968777]=perlquestion: print w/replies, xml ) Need Help??

mmusser has asked for the wisdom of the Perl Monks concerning the following question:

Hi folks. I've got about 3 months experience with Perl under my belt from the U, and am trying my hand at arguments for the first time. At first, it seemed to be working fine, but using args is not mixing well with prompting for user input. Just wondering how I'm doing this wrong:

#!/usr/bin/perl use warnings; use strict; use Date::Calc qw( Today Add_Delta_Days ); # This program takes input from a data dump # (CSV format) and produces the migration prep file # with very little user input at prompt. my $file = $ARGV[0]; my $num_args = $#ARGV + 1; die "ERROR: Usage: prep_gen.pl subs_dump_file.csv\nPlease provide file + name\n" if ($num_args != 1); #Confirm .csv format my $period = rindex($file, "."); die "Invalid file format; must be .csv extension.\n" if ($period == -1 +); die "Invalid file format; must be .csv extension.\n" if (uc(substr($fi +le, $period)) !~ /\.CSV$/); my $fileName = substr($file, 0, $period); open(my $infile, "<", $file) or die "Cannot open $file for reading!\n" +; open(my $outfile, ">", $fileName."-migration-prep.txt") or die "Cannot + open outfile for writing!\n"; # This will be the prep file create +d # We need the merchant name and customer ID # This is the only prompted input print "Please provide the full merchant name: \n"; my $merchName = <>; chomp($merchName); print $outfile "completeMerchantName=$merchName\n"; # Start adding +content to outfile my ($year, $month, $day) = Today(); # Calc today's date for nex +t date calc ($year, $month, $day) = Add_Delta_Days($year,$month,$day,60); # Con +clude date for migration will be +60 days $month = sprintf("%02d", $month+1); $day = sprintf("%02d", $day); print "NOTE: migration conclude date set to $year-$month-$day 00:00:00 +\n"; print $outfile "cleanupDate=$year-$month-$day 00:00:00\n"; print "Please provide the customer ID as it appears in the DB: \n"; my $customerId = <>; chomp($customerId); while ($customerId !~ /^[0-9]+$/) { # Customer ID must be numer +ic print "Invalid input; customer ID must be completely numeric. Plea +se try again: \n"; chomp($customerId = <>); } print $outfile "subscriptionDb.customerId=$customerId\n";

When I run this, I get a bunch of errors about uninitialized values, and it's not asking for some input like I need it to:

mmusser@localhost:~/programming/perl$ perl prep_gen.pl some_file.csv Please provide the full merchant name: NOTE: migration conclude date set to 2012-08-02 00:00:00 Please provide the customer ID as it appears in the DB: Use of uninitialized value $customerId in scalar chomp at prep_gen.pl +line 50, <> line 1. Use of uninitialized value $customerId in pattern match (m//) at prep_ +gen.pl line 52, <> line 1. Invalid input; customer ID must be completely numeric. Please try agai +n:

However, if I don't use arguments and just prompt the user for a file name, everything works as I expect it to. Thanks in advance for any and all help!

Replies are listed 'Best First'.
Re: First time using Args
by JavaFan (Canon) on May 03, 2012 at 17:13 UTC
    You want to explicitly read from STDIN, not the magical ARGV, which only reads from STDIN if no argument are given (or to be precise, if @ARGV is empty). Replace your <> with <STDIN>.

    And as a general advice: avoid write tools that ask the user questions: arguments are more flexible, as it makes piping and scripting easier. Imagine that each time you would run perl from the command line, it starts with:

    $ perl Do you want to enable warnings? [y/N] n Do you want to loop over the input? [y/N] y You want to loop over the input. Print $_ each time? [y/N] ... 40 questions later ... Please type your one-liner, ending with a newline
      Fascinating. In Programming class, we were taught that <> = <STDIN>. I didn't know they were actually different. Thanks very much for your help :). I could write this without asking for user input...the only problem was that one of the args would be a string that may contain spaces, and I'm not sure how best to handle that. Make the user enter that argument with quotes?
        In Programming class, we were taught that <> = <STDIN>.
        That's wrong. <> is shorthand for <ARGV>.
        I could write this without asking for user input...the only problem was that one of the args would be a string that may contain spaces, and I'm not sure how best to handle that. Make the user enter that argument with quotes?
        Quotes, or backslashes should work in all shells that I know off. (The spaces are special to the shell, Perl has nothing to do with that).
Re: First time using Args
by Not_a_Number (Prior) on May 03, 2012 at 19:03 UTC

    Hi.

    A couple of other remarks:

    • You go to a lot of trouble to validate and then open the input file given on the command line, but then you never actually read from the said file...

    • You increment month by 1 in this line:
      $month = sprintf("%02d", $month+1);

      but, as you have already added 60 days, this will add a further 30 (or 31, or 28, or whatever).

    • In fact, assuming that you don't want to increment month, that whole chunk of code (four lines) could be simplified to:
    • my $deadline = sprintf '%d-%02d-%02d 00:00:00', Add_Delta_Days( Today, 60 );

      Ah,thanks for the tip on the date. I'm still making lots of newbish mistakes. Yeah, I don't validate the contents of the file itself...haven't thought about how I'd go about doing that yet. The script itself is far from finished, actually, but I've never validated the content of a file to check its format.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (2)
As of 2024-04-19 20:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found