Missing Words has asked for the wisdom of the Perl Monks concerning the following question:
I am currently modifing a subroutine(later to be added to a module) which I use often. The subroutine's name is masked_read. I have prototyped it to take two optional arguments, one being a scalar variable, and the other being any scalar like so: sub masked_read(;\$$). However, I have two questions:
use Term::ReadKey; sub masked_read(;\$$) { my $mask; if($_[1]){ if(length $_[1] > 1){ die "arg 2 of masked_read() should only be 1 character long"; } $mask = $_[1]; } else{ $mask="*"; } my $key; $|=1; while(1) { while(not defined($key = ReadKey(-1))) {}; if(ord($key) != 13) { if(ord($key) == 8) { print "\b \b"; chop(${$_[0]}); } else { ${$_[0]} .= $key; print "$mask"; } } else {last} } $|=0; return ${$_[0]}; } print "Enter:"; my $password = masked_read; print "\npassword:$password";
masked_read($password, $mask); masked_read($password, '#'); masked_read($password); my $password = masked_read();
However, I would like the user to also have the following option: $password = masked_read('#')
I have already considered simply switching the order of the two parameters; however, that leads to syntax such as:
masked_read('#',$password) . Which is counterintuitive and creates the problem of getting the scalar variable when the first value is not present.
I have also thought of creating a if-then structure to determine what the user has passed, but cannot think of or find a way to determine whether something is a variable or not.
This issue is the one that has stumped me, and any direction at all would be helpful.
Second Question:
As you can see I am currently using the length function to catch arguments in $_[1] that is more than one character. Right now this is needed because the method I use to mask the password on the screen does not work with a mask of more than one character if the person enters a backspace. This works fine, however I was wondering if there was a more efficient way of doing this. I looked through most of the information I have on prototyping and I did not see any way to accomplish it through prototyping means. If anyone knows of an alternative, it would be very helpful.
I realize this subroutine is pretty trite however I am doing this mostly as a means to learn about prototyping, subroutines, and later, making modules.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Subroutine Prototyping/Subroutine Argument Parsing
by BrowserUk (Patriarch) on Jun 08, 2003 at 07:12 UTC | |
Re: Subroutine Prototyping/Subroutine Argument Parsing
by sauoq (Abbot) on Jun 08, 2003 at 08:31 UTC | |
Re: Subroutine Prototyping/Subroutine Argument Parsing
by broquaint (Abbot) on Jun 08, 2003 at 10:28 UTC | |
Re: Subroutine Prototyping/Subroutine Argument Parsing
by Missing Words (Scribe) on Jun 08, 2003 at 14:25 UTC |