[plug] bash to perl

Derek Fountain derekfountain at yahoo.co.uk
Sun Nov 2 14:12:53 WST 2003


> I have a bash script that when it runs has a first executable line which
> reads:
>
> . /etc/file
>
> This sets up a number of variables.
> The file looks like:
>
> PAGER=less
>
> I want to change / import the same variables into a perl version of my bash
> script.

The "correct" way to do that in Perl would be to build a hash. If 'file.txt' 
contains:

PAGER=more
DEBUG=0

then something like this would work:

---
#!/usr/bin/perl -w
use strict;

my %importedVars = ();

open HANDLE, "<file.txt" or die "dead";
while( <HANDLE> ) {
  chomp;
  my( $var, $value ) = split( /\s*=\s*/, $_, 2);

  $importedVars{$var} = $value;
}
close( HANDLE );

print $importedVars{PAGER}, "\n";
print $importedVars{DEBUG}, "\n";
---

Perl is stricter than bash about creating and using variables. Just having a 
variable appear from nowhere confuses the compiler, so the above technique 
imports the values into a known hash (%importedVars).

-- 
> eatapple
core dump

_______________________________________________
plug mailing list
plug at plug.linux.org.au
http://mail.plug.linux.org.au/cgi-bin/mailman/listinfo/plug


More information about the plug mailing list