Tech and travel

Asking for a value in Perl

2007-09-20

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=<stdin>);
  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.

Copyright (c) 2024 Michel Hollands