【问题标题】:Hiding STDIN echo after pressing Enter按 Enter 后隐藏 STDIN 回显
【发布时间】:2014-10-08 14:01:19
【问题描述】:

我正在开发一个使用 unix 终端的消息系统,因此为了使消息输出更加用户友好,我想在按下回车按钮后隐藏 <STDIN> 输入以在另一个消息输出中使用它。

my $user = "Someone";
my $message = <STDIN>; #must show what does user type but should hide the message after pressing enter
chomp $message;
print messagefile "<$user> $message\n";

我在论坛上看到一些方法正在使用Term::ReadKey,但不幸的是我无法做到这一点,因为该模块不存在于系统中。

【问题讨论】:

  • 用 CPAN 或 cpanm Term::ReadKey 安装缺少的模块,如果你有 apt-get 你可以试试 apt-get install libterm-readkey-perl
  • 如果可以的话,我会的,我没有权限,也无法要求管理。我正在寻找另一种方式
  • 出于好奇,隐藏您刚刚输入的内容如何使消息传递系统更加用户友好?难道你不想看到所说的记录吗?
  • 我不确定“我无法询问管理人员”是什么意思。你被禁止与他们交谈吗?但是说真的,如果你在一个 Perl 环境中,你认为你不能安装模块(顺便说一下,that's never the case),那么这就是你的 Perl 编程的主要障碍,你应该先解决这个问题。 .

标签: linux perl stdin


【解决方案1】:

借用from answer。它一次读取一个字符,当按下回车时,它会用\r &lt;spaces&gt; \r擦除当前行

use strict;
use warnings;

sub get_pass {

  local $| = 1;
  my $ret = "";
  while (1) {
    my $got = getone();
    last if $got eq "\n";

    print $got;
    $ret .= $got;
  }
  print "\r", " " x length($ret), "\r";
  return $ret;
}

my $user = "Someone";
my $message = get_pass();
chomp $message;
print "<$user> $message\n";


BEGIN {
  use POSIX qw(:termios_h);

  my ($term, $oterm, $echo, $noecho, $fd_stdin);

  $fd_stdin = fileno(STDIN);

  $term     = POSIX::Termios->new();
  $term->getattr($fd_stdin);
  $oterm     = $term->getlflag();

  $echo     = ECHO | ECHOK | ICANON;
  $noecho   = $oterm & ~$echo;

  sub cbreak {
      $term->setlflag($noecho);
      $term->setcc(VTIME, 1);
      $term->setattr($fd_stdin, TCSANOW);
  }

  sub cooked {
      $term->setlflag($oterm);
      $term->setcc(VTIME, 0);
      $term->setattr($fd_stdin, TCSANOW);
  }

  sub getone {
      my $key = '';
      cbreak();
      sysread(STDIN, $key, 1);
      cooked();
      return $key;
  }

}
END { cooked() }

【讨论】:

    【解决方案2】:

    来自http://www.perlmonks.org/?node_id=33353

    use autodie qw(:all);
    
    print "login: ";
    my $login = <>;
    print "Password: ";
    system('stty', '-echo');  # Disable echoing
    my $password = <>;
    system('stty', 'echo');   # Turn it back on
    

    【讨论】:

    • 不,它仍然会将输入的消息保留在屏幕上
    • 您使用的是什么终端类型?
    • 当我测试它可以工作时,我也更新了系统调用
    • 是的,但是你能看到用户在那一行输入了什么吗?在按下回车按钮之前它不显示消息,它实际上应该显示我正在输入什么密码,但是在接受它之后,该行应该消失
    猜你喜欢
    • 1970-01-01
    • 2011-05-03
    • 2011-11-11
    • 2014-06-08
    • 1970-01-01
    • 2021-06-14
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多