can we source a shell script in perl script

前端 未结 7 752
隐瞒了意图╮
隐瞒了意图╮ 2021-01-15 04:54

can we source a shell script in the perl script??

Example: Program 1:

cat test1.sh
#!/bin/ksh
DATE=/bin/date

program 2:

<         


        
相关标签:
7条回答
  • 2021-01-15 05:33

    You can't source shell files in Perl 5. Sourcing is literally running the commands in the shell file in the target shell; however, it is trivial to open and read the file:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Carp;
    
    sub source {
        my $file = shift;
        open my $fh, "<", $file
            or croak "could not open $file: $!";
    
        while (<$fh>) {
            chomp;
            #FIXME: this regex isn't quite good enough
            next unless my ($var, $value) = /\s*(\w+)=([^#]+)/;
            $ENV{$var} = $value;
        }
    }
    
    source "./test1.sh";
    
    print "$ENV{DATE}\n";
    
    0 讨论(0)
提交回复
热议问题