让 Perl Getopt::Long 在字符串中保留反斜杠 (\)
我的一位同事编写了一个 perl 脚本,要求用户输入 Windows 域名/用户名,当然我们输入以下格式域名\用户名
。然后,Getopt:Long 模块将其转换为字符串,删除“\”字符并导致字符串不正确。当然,我们可以要求所有用户输入他们的域/用户组合作为 domainname\\username
但我真的不想有罪“修复用户,而不是程序”。我们还使用为此创建的模块,我将调用 OurCompany::ColdFusionAPI
因为它访问 ColdFusion。
我们的代码如下所示:
#!/usr/bin/perl
use common::sense;
use Getopt::Long;
use OurCompany::ColdFusionAPI;
my ($server_ip, $username, $password, $need_help);
GetOptions (
"ip|server-address=s" => \$server_ip,
"user-name=s" => \$username,
"password=s" => \$password,
"h|help" => \$need_help,
);
$username ||= shift;
$password ||= shift;
$server_ip ||= shift;
if (!$server_ip or $need_help){
print_help();
exit 0;
}
my $print_hash = sub { my $a = shift; say "$_\t=> $a->{$_}" foreach keys %$a; };
...
如果我添加行 say $username
那么它只会给出不带“\”的字符串。我怎样才能让perl保留'\'?类似于 bash 中的 read -r
的内容。
One of my colleagues wrote a perl script that asks for the user's windows domain/user name, which of course we enter the the following format domainname\username
. The Getopt:Long module then converts this into a string dropping out the '\' character and rendering the string incorrect. Of course, we could just ask all our users to enter their domain/user combo as domainname\\username
but I really don't want to be guilty "fix the user, not the programme". We also use a module we made for this, I'll call OurCompany::ColdFusionAPI
since it accesses ColdFusion.
Our code looks like this:
#!/usr/bin/perl
use common::sense;
use Getopt::Long;
use OurCompany::ColdFusionAPI;
my ($server_ip, $username, $password, $need_help);
GetOptions (
"ip|server-address=s" => \$server_ip,
"user-name=s" => \$username,
"password=s" => \$password,
"h|help" => \$need_help,
);
$username ||= shift;
$password ||= shift;
$server_ip ||= shift;
if (!$server_ip or $need_help){
print_help();
exit 0;
}
my $print_hash = sub { my $a = shift; say "$_\t=> $a->{$_}" foreach keys %$a; };
...
If I add the line say $username
then it just gives the string without the '\'. How can I get perl to keep the '\'? Something along the lines of read -r
in bash.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 shell 会执行此操作,而不是 Getopt::Long。您需要对
\
进行转义,以便 shell 将其解释为文字反斜杠,而不是尝试转义某些内容。Your shell does that, not Getopt::Long. You need to escape the
\
in order for your shell to interpret it as a literal backslash rather than an attempt to escape something.您确定这是由于 Getopt::Long 造成的吗?很可能你的 shell 已经在解析你正在输入的内容,并弄乱了反斜杠。
为什么不分别询问域名和用户名?这会比较优雅地解决这个问题。
Are you sure this is due to Getopt::Long? Most likely your shell is already parsing what you're typing, and messing with the backslashes.
Why not ask Domain and Username seperately? That would solve the problem somewhat elegantly.