【问题标题】:What's wrong with this [duplicate]这有什么问题[重复]
【发布时间】:2013-02-24 16:00:07
【问题描述】:

我需要检查配置文件是否存在,所以我写这个是为了测试目的

#!/usr/bin/perl
use strict;
use warnings;

my $prfle=`~/sqllib/db2profile`;
print $prfle;

但它什么也没打印...

脚本检查配置文件,如果找不到,它将询问用户,直到提供有效路径并执行该配置文件,我在 shell 脚本中成功实现了这一点,但在 perl 中遇到了问题

【问题讨论】:

标签: perl


【解决方案1】:

在 Perl 中,反引号执行一个 shell 命令。例如,这将打印 hi:

`echo hi`;

要检查文件是否存在,请使用-e:

$prfle= '~/sqllib/db2profile';
if (-e $prfle) {
    print "File Exists!\n";
}

注意字符串文字周围的单引号',而不是反引号`

【讨论】:

  • prfile=~/sqllib/db2profile profile() { if [ -f $prfile ] && [ "$prfile" != "" ]; then . $prfile else read -p "Enter a valid Profile : " prfile profile fi } profile 我如何在 perl 中做到这一点
  • 看起来@TLP 提供了您的 bash 脚本的 Perl 版本 :)
【解决方案2】:

根据你的 cmets,我怀疑你想要这样的东西:

my $profile = '';                     # default profile
while (not -e $profile) {             # until we find an existing file
    print "Enter a valid profile: "; 
    chomp($profile = <>);             # read a new profile 
}
qx($profile);                         # execute this file

执行文件的选项不止一种。 qx() 与反引号相同,将返回标准输出。 system() 将返回系统给出的执行命令的返回值。 exec() 将执行命令并退出您的 perl 脚本,有效地忽略 exec 之后的任何代码。根据您的需要,选择最适合您的选项。

【讨论】:

  • 嗨,你是写的,但我唯一需要的是,通常配置文件位于 home-directory/sqllib/bin~/sqllib /bin ,所以如果在那里找不到,那么我们会要求提供有效的配置文件
  • 然后输入“默认配置文件”。
  • 你没有得到我,这就是我的意思 my $profile = '~/sqllib/db2profile'; 给了我 ~/sqllib/db2profile 而不是 /home-dir/sqllib/db2profile
  • 你是说 perl 不能识别~/ 语法吗?我认为shell中的~/$HOME是一样的?在这种情况下,您可以尝试$ENV{'HOME'}/sqllib/db2profile
  • 我试试看告诉你
猜你喜欢
  • 1970-01-01
  • 2016-10-08
  • 2020-06-17
  • 2021-09-11
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多