Created
September 19, 2014 14:50
-
-
Save charliek/51af5782820ab0eed770 to your computer and use it in GitHub Desktop.
Simple perl environment variable substitution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
my $num_args = $#ARGV + 1; | |
if ($num_args != 2) { | |
print "\nUsage: vsub.pl [input file] [output file]\n"; | |
exit 1; | |
} | |
# Slurp whole file into content variable | |
my $file_name = $ARGV[0]; | |
my $output_file = $ARGV[1]; | |
open my $fh, $file_name or die "Could not open $file_name: $!"; | |
local $/; # enable localized slurp mode | |
my $content = <$fh>; | |
close $fh; | |
# Replace all keys in the environment with the value | |
foreach my $key (keys %ENV) { | |
$key = quotemeta $key; # escape regex metachars if present | |
$content =~ s/#{$key}/$ENV{$key}/g; | |
} | |
open (OUTFILE, ">>$output_file"); | |
print OUTFILE $content; | |
close (OUTFILE); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment