如何将shell脚本移植到Perl?

时间:2013-02-24 16:23:04

标签: perl

这是一个shell脚本,如何在Perl中完成同样的事情?

prfile=~/sqllib/db2profile

profile()
{
if [ -f $prfile ] && [ "$prfile" != "" ];
then
        . $prfile
else
        read -p "Enter a valid Profile : " prfile
        profile
fi
}
profile

这里检查配置文件,如果发现它用. $prfile执行它,否则它会再次询问用户是否有正确的配置文件

更新

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

my $profile = "$ENV{'HOME'}/sqllib/db2proile";
# 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);

这很有用。我希望主目录是动态的而不是硬编码的,因为它们因不同的机器而不同。我只是想用Perl完成我用shell实现的目标。

1 个答案:

答案 0 :(得分:0)

如果我了解你的目标,我认为你不能使用perl来完成这个,因为perl将作为子进程运行,它不能改变shell的环境(它是父进程)。也许这对你有用(未经测试,不在袖口)?

prfile=~/sqllib/db2profile
if [ -s "$prfile" ] ; then
   . "$prfile"
else
  while true ; do 
    read -p "Enter a valid Profile : " prfile
    if [ -s "$prfile" ] ; then
       . "$prfile"
       break;
    fi
  done
fi