Skip to content

Instantly share code, notes, and snippets.

@charliek
Created September 19, 2014 14:50
Show Gist options
  • Save charliek/51af5782820ab0eed770 to your computer and use it in GitHub Desktop.
Save charliek/51af5782820ab0eed770 to your computer and use it in GitHub Desktop.
Simple perl environment variable substitution
#!/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