Skip to content

Asking for a value in Perl

The following Perl snippet is useful if you want to ask for a value from the user. The get_new_value function takes the variable name and a default value as parameter. These are printed on screen. The default value is used if no input is given.

  use strict;

  sub get_new_value {
    my($param_name, $param_current_value) = @_;

    print "$param_name [$param_current_value] :";
    chomp(my $input=);
    my $new_value = $input eq "" ? $param_current_value : $input;
    return $new_value;
  }

  my $var = get_new_value('VAR', $ENV{VAR});

The output looks like this (this script was saved to set_params.pl) :

  $ export VAR="/usr/bin"
  $ perl set_params.pl
  VAR [/usr/bin] :

If no value is given and enter is pressed, $var is set to /usr/bin.