File: ENVDumper.pm

package info (click to toggle)
liblocal-lib-perl 2.000029-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 344 kB
  • sloc: perl: 1,141; makefile: 13
file content (60 lines) | stat: -rw-r--r-- 1,121 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package ENVDumper;
use strict;
use warnings;

our @EXPORT_OK = qw(dumpenv undump);

my %trans = (
  "\0" => "\\0",
  "\r" => "\\r",
  "\n" => "\\n",
  "\t" => "\\t",
  "\f" => "\\f",
  "\b" => "\\b",
  "\a" => "\\a",
  "\e" => "\\e",
  "\\" => "\\\\",
);

my %reverse = reverse %trans;

sub import {
  my ($class, @args) = @_;
  if (grep $_ eq '--dump', @args) {
    print dumpenv();
    exit 0;
  }
  elsif (@args) {
    require Exporter;
    goto &Exporter::import;
  }
}

sub dumpenv {
  my $out = '';
  my ($match) = map qr/$_/, join ('|', map quotemeta, sort keys %trans);
  for my $key (sort keys %ENV) {
    my $value = $ENV{$key};
    $value = '' unless defined $value;
    s/($match)/$trans{$1}/g
      for ($key, $value);
    $out .= "$key\t$value\n";
  }
  $out;
}

sub undump {
  my $in = shift || '';
  my $out = {};
  my ($match) = map qr/$_/, join ('|', map quotemeta, sort keys %reverse);
  my @lines = split /\r\n?|\n/, $in;
  for my $line (@lines) {
    my ($key, $value) = split /\t/, $line, 2;
    $_ && s/($match)/$reverse{$1}/g
      for ($key, $value);
    $out->{$key} = $value;
  }
  $out;
}

1;