Accepting user input

This page shows different ways to accept user input using perl.

Accepting user input from the command line

There are a number of ways to accept command line input. Firstly you can use the @ARGV array:

    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:

    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:

    ./ -p -t hello

The output would be:

    p was passed in.
    t has a value of: hello

Accepting user input from a terminal

You can read directly from standard in with the angle operators <>.

    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 (<>) {

Accepting user input graphically

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.

    use strict;
    use warnings;
    use Tk;

    my $mw = MainWindow->new;
    my $text;

    $mw->title("Text Entry");

        -text => "Enter some text:"

        -textvariable => \$text

        -text => "Click here",
        -command =>
            sub {
                print "You typed: $text\n";

        -text => "Done",
        -command => sub {exit}


    exit 0;

Accepting user input from a web form

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:

    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;

See also

    perldoc perlvar
    perldoc Getopt::Std
    perldoc Tk
    perldoc CGI
Revision: 1.4 [Top]