gpt4 book ai didi

perl - 如果在命令行中没有输入参数,则显示错误

转载 作者:行者123 更新时间:2023-12-04 07:58:10 25 4
gpt4 key购买 nike

我需要编写一个程序来读取 Linux 中的 passwd 文件。用户输入程序名称和想要的用户名,然后程序打印出对应的userID和homeDir。如果未提供用户名或输入了多个用户,程序将显示错误消息。

Good ex)
User types:
lookupUser.pl jdoe123
Result:
UID: 123456
HomeDir: /home/jdoe123

Bad ex)
User types:
lookupUser.pl
Result:
Enter one, and only one username.

Bad ex)
User types:
lookupUser.pl jdoes123 ssanta456
Result:
Enter one, and only one username.
在某个时候,我让一切正常,但我开始清理代码,现在当我没有输入用户名时出现错误“ Use of uninitialized value $user in scalar chomp at ./lookupUser.pl line 6.”。
任何帮助是极大的赞赏。
#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';

my $user = $ARGV[0];
chomp ($user);

if ($#ARGV == -1 || $#ARGV >= 1){
print "Enter one, and only one username.\n";
}

elsif (getpwnam("$user")) {
(my $name, my $passwd, my $uid, my $gid, my $quota, my $comment,
my $gcos, my $dir, my $shell) = getpwnam $user;
#print "Name = $name\n";
#print "Password = $passwd\n";
print "UID = $uid\n";
#print "GID = $gid\n";
#print "Quota = $quota\n";
#print "Comment = $comment\n";
#print "Gcos = $gcos\n";
print "HOME DIR = $dir\n";
#print "Shell = $shell\n";
}
else {
print "Username $user does not exist.\n";
}

最佳答案

只有当正好有 1 个参数传递给程序时,才检查用户名。

use strict;
use warnings FATAL => 'all';

if (@ARGV == 1 ) {
my $user = $ARGV[0];
chomp ($user);
if (getpwnam("$user")) {
(my $name, my $passwd, my $uid, my $gid, my $quota, my $comment,
my $gcos, my $dir, my $shell) = getpwnam $user;
print "UID = $uid\n";
print "HOME DIR = $dir\n";
}
else {
print "Username $user does not exist.\n";
}
}
else {
print "Enter one, and only one username.\n";
}

关于perl - 如果在命令行中没有输入参数,则显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66592890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com