Home » Howtos » Using perl » Accept user input |
This page shows different ways to accept user input using perl.
There are a number of ways to accept command line input. Firstly you can use the @ARGV array:
#!/usr/bin/perl use strict; use warnings; print $ARGV[0] . "\n";
Note that $ARGV[0] actually is the first argument and not the program name.
Or if you need a bit more flexibility, use the Getopt::Std module:
#!/usr/bin/perl use strict; use warnings; use Getopt::Std; my %args; # -p is just a flag # -t has a value getopts('pt:', \%args); if ($args{p}) { print "p was passed in.\n"; } if ($args{t}) { print "t has a value of: $args{t}\n"; }
If you called the above program as follows:
./test.pl -p -t hello
The output would be:
p was passed in. t has a value of: hello
You can read directly from standard in with the angle operators <>.
#!/usr/bin/perl use strict; use warnings; while (<STDIN>) { last if ($_ =~ /^\s*$/); # Exit if it was just spaces (or just an enter) print "You typed: $_"; }
You could use the angle operators without the word 'STDIN':
while (<>) {
The code below will display a perl Tk widget, with text field and two buttons. Enter some text in the text field then press the 'Click here' button. You will see the text you typed appear in your terminal. When you are finished click the 'Done' button.
#!/usr/bin/perl use strict; use warnings; use Tk; my $mw = MainWindow->new; my $text; $mw->title("Text Entry"); $mw->Label( -text => "Enter some text:" )->pack(); $mw->Entry( -textvariable => \$text )->pack(); $mw->Button( -text => "Click here", -command => sub { print "You typed: $text\n"; } )->pack(); $mw->Button( -text => "Done", -command => sub {exit} )->pack(); MainLoop; exit 0;
Use the CGI module, create a CGI object (in the variable $q in our case), and call the CGI method param() to retrieve the form values. The example below also prints out the form:
#!/usr/bin/perl use strict; use warnings; use CGI; use CGI::Carp qw(fatalsToBrowser); my $q = new CGI; print $q->header(); print $q->start_html( -style => qq( body {font-family: verdana, arial, sans-serif;} ) ); if ($q->param()) { print "Your name is " . $q->param('username') . "<BR>"; print $q->br; } # Output the form print $q->start_form(); print "Name: "; print $q->textfield(-name => "username"); print $q->br; print $q->submit(-value => "Click here"); print $q->end_form(); print $q->end_html(); exit 0;
perldoc perlvar perldoc Getopt::Std perldoc Tk perldoc CGI