<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#!/usr/bin/perl
use strict;
use Storable;
my $VERSION = 1.5;

#=Description
# Simple editor for files saved with storable.

# Read file
my $filename=shift;
my $data;
if (! $filename) {
	print 'This is storableedit.pl, version ', $VERSION, "\n";
	print "\n";
	print 'Usage: storableedit.pl FILE', "\n";
	print '       where FILE is a Perl Storable file', "\n";
	print "\n";
	print 'For more information, check out', "\n";
	print '    perldoc storableedit.pl', "\n";
	exit;
} elsif (-f $filename) {
	StorableEdit-&gt;done('Opening file: ', $filename);
	$data=retrieve($filename);
} else {
	StorableEdit-&gt;done('Creating new file: ', $filename);
	$data={};
}

# Edit
my $e=StorableEdit-&gt;new($data);
my $dosave=$e-&gt;edit();

# Save
if ($dosave) {
	store $e-&gt;data(), $filename;
	StorableEdit-&gt;done('File saved: ', $filename);
}

exit;

package StorableEdit;
use Storable;
use Term::ReadLine;

sub new {
	my $o=shift;
	my $class=(ref($o) || $o);
	my $newo=bless {}, $class;
	$newo-&gt;init(@_);
	return $newo;
}

# Initializing.
sub init {
	my $o=shift;
	my $data=shift;

	$o-&gt;data($data);
	$o-&gt;{'changed'}=0;
	$o-&gt;{'readline'}=Term::ReadLine-&gt;new('StorableEdit');
	return;
}

# Returns the data.
sub data {
	my $o=shift;
	if (my $set=shift) {
		$o-&gt;{'data'}=$set;		# Data
		$o-&gt;{'pathobjects'}=[];	# Path objects
		$o-&gt;{'path'}=[];		# Path to cur
		$o-&gt;{'cur'}=$set;		# Currently selected branch
	}
	return $o-&gt;{'data'};
}

# Sets the changed flag.
sub setchanged {
	my $o=shift;
	$o-&gt;{'changed'}=1;
	return;
}

# Returns the changed flag.
sub changed {
	my $o=shift;
	return $o-&gt;{'changed'};
}

# Lets the user edit the structure.
sub edit {
	my $o=shift;
	
	# Show contents
	$o-&gt;show($o-&gt;{'data'}, 50);

	# Command loop
	while (1) {
		my $cmd=$o-&gt;input();

		if (($cmd eq 'quit') || ($cmd eq 'q')) {
			if ($o-&gt;changed()) {
				$o-&gt;error('Changes were made. Use "q!" to quit without saving or "x" to save and quit.');
			} else {
				return 0;
			}
		} elsif (($cmd eq 'quit!') || ($cmd eq 'q!')) {
			return 0;
		} elsif (($cmd eq 'exit') || ($cmd eq 'x')) {
			return 1;
		} elsif ($cmd eq 'help') {
			print 'Commands:', "\n";
			print '  x, exit:  save and quit', "\n";
			print '  q, quit:  quit without saving', "\n";
			print '  l, ls:    list items in current object/reference', "\n";
			print '  cd ITEM:  dive into item (must be reference)', "\n";
			print '  cd ..:    go up', "\n";
			print '  cd ...:   go 2 steps up', "\n";
			print '  other:    evaled as perl code', "\n";
			print '            $cur: variable of current object/reference', "\n";
			print '            $base: variable of base object/reference', "\n";
			print '', "\n";
			print 'Examples:', "\n";
			print '  $cur-&gt;{\'test\'}=\'hello world\'', "\n";
			print '  $cur-&gt;{\'fruits\'}=[\'apple\', \'banana\']', "\n";
			print '  $cur-&gt;{\'available\'}={\'apple\' =&gt; 1, \'banana\' =&gt; 5}', "\n";
			print '  cd available', "\n";
			print '  l', "\n";
			print '  bless $cur, \'MyObject\'', "\n";
			print '  $cur-&gt;{\'imported\'}=retrieve(\'importfile.store\')', "\n";
			print '  store($cur, \'exportfile.store\')', "\n";
			print '  $data=$cur', "\n";
			print '', "\n";
			print 'For a more complete help, see', "\n";
			print '    perldoc storableedit.pl', "\n";
		} elsif ($cmd eq 'l') {
			$o-&gt;show($o-&gt;{'cur'}, 50);
		} elsif ($cmd eq 'ls') {
			$o-&gt;show($o-&gt;{'cur'});
		} elsif ($cmd =~ /^cd\s+(.*?)$/) {
			my $cd=$1;
			$o-&gt;cd($cd);
		} elsif ($cmd eq 'cd') {
		} elsif ($cmd eq '..') {
			$o-&gt;cd('..')
		} elsif ($cmd eq '...') {
			$o-&gt;cd('...')
		} elsif ($cmd) {
			$o-&gt;setchanged();
			my $cur=$o-&gt;{'cur'};
			my $data=$o-&gt;{'data'};

			undef $@;
			undef $!;
			eval $cmd;

			if ($@) {
				$o-&gt;error('Eval error: ', $@);
			} elsif ($!) {
				$o-&gt;error('Eval error: ', $!);
			} elsif ($data!=$o-&gt;{'data'}) {
				if (ref $data) {
					$o-&gt;data($data);
					$o-&gt;done('New base object set!');
				} else {
					$o-&gt;error('The base object must be a reference (HASH, ARRAY or REF).');
				}
			} elsif ($cur!=$o-&gt;{'cur'}) {
				$o-&gt;error('You cannot change the current branch this way. Use "cd" instead.');
			}
		}
	}
	
	return;
}

sub cd {	# cd($cdpath)
	my $o=shift;
	my $cdpath=shift;
	
	my $pathinfo={
		'node'	=&gt; $o-&gt;{'cur'},
		'path'	=&gt; [@{$o-&gt;{'path'}}],
		'pathobjects'	=&gt; [@{$o-&gt;{'pathobjects'}}],
		};
	
	$pathinfo=$o-&gt;cdpath($pathinfo, $cdpath);
	return if (! ref $pathinfo);
	
	$o-&gt;{'cur'}=$pathinfo-&gt;{'node'};
	$o-&gt;{'path'}=$pathinfo-&gt;{'path'};
	$o-&gt;{'pathobjects'}=$pathinfo-&gt;{'pathobjects'};
	return;
}

sub cdpath {	# $node = cdpath($pathinfo, $cdpath)
	my $o=shift;
	my $pathinfo=shift;
	my $cdpath=shift;
	
	my @path=split(/\//, $cdpath);
	foreach my $label (@path) {
		$pathinfo=$o-&gt;cdstep($pathinfo, $label);
		return if (! ref $pathinfo);
	}
	
	return $pathinfo;
}

# Change directory.
sub cdstep {	# $node = cdstep($node, $cd)
	my $o=shift;
	my $pathinfo=shift;
	my $cd=shift;
	
	my $node=$pathinfo-&gt;{'node'};
	my $path=$pathinfo-&gt;{'path'};
	my $pathobjects=$pathinfo-&gt;{'pathobjects'};

	my $type=$o-&gt;type($node);
	if ($cd eq '..') {
		if (scalar(@$path)&gt;0) {
			pop @$path;
			$pathinfo-&gt;{'node'}=pop @$pathobjects;
			return $pathinfo;
		}
	} elsif ($cd eq '...') {
		$pathinfo=$o-&gt;cdstep($pathinfo, '..');
		$pathinfo=$o-&gt;cdstep($pathinfo, '..');
		return $pathinfo;
	} elsif ($type eq 'ARRAY') {
		my $newcur=$node-&gt;[$cd];
		if (ref $newcur) {
			push @$path, $cd;
			push @$pathobjects, $node;
			$pathinfo-&gt;{'node'}=$newcur;
			return $pathinfo;
		} else {
			$o-&gt;error('Cannot change into non-reference (', $cd, ').');
		}
	} elsif ($type eq 'HASH') {
		my $newcur=$node-&gt;{$cd};
		if (ref $newcur) {
			push @$path, $cd;
			push @$pathobjects, $node;
			$pathinfo-&gt;{'node'}=$newcur;
			return $pathinfo;
		} else {
			$o-&gt;error('Cannot change into non-reference (', $cd, ').');
		}
	} elsif ($type eq 'REF') {
		my $newcur=$$node;
		if (ref $newcur) {
			push @$path, 'ref';
			push @$pathobjects, $node;
			$pathinfo-&gt;{'node'}=$newcur;
			return $pathinfo;
		} else {
			$o-&gt;error('Cannot change into non-reference (', $cd, ').');
		}
	} else {
		$o-&gt;error('Unexpected error.');
	}

	return;
}

# Lets the user give an input.
sub input {
	my $o=shift;
	
	my @cmd;
	my $line=$o-&gt;inputline(1);
	while ($line =~ /^\s*(.*)\s*\\$/) {
		push @cmd, $1;
		$line=$o-&gt;inputline(0);
	}
	$line=$1 if ($line =~ /^\s*(.*)\s*$/);
	push @cmd, $line;
	return join("\n", @cmd);
}


# Lets the user give an input.
sub inputline {	# $cmd = inputline($showpath)
	my $o=shift;
	my $showpath=shift;
	my $path=$o-&gt;{'path'};
	my $cur=$o-&gt;{'cur'};
	my $readline=$o-&gt;{'readline'};

	# Path
	print "\n" if ($showpath);
	my $prompt=chr(033).'[0;33m';
	$prompt.='/'.join('/', @$path) if ($showpath);
	$prompt.=' ('.ref($cur).')' if ($showpath);
	$prompt.='&gt; '.chr(033).'[0m';

	# Get user input
	my $cmd=$readline-&gt;readline($prompt);
	return if (! defined $cmd);
	while (chomp $cmd) {}
	$readline-&gt;addhistory($cmd);
	return $cmd;
}

# Displays contents.
sub show {
	my $o=shift;
	my $data=shift;
	my $textlimit=shift;
	
	# Data
	my $type=$o-&gt;type($data);
	if ($type eq 'ARRAY') {
		return $o-&gt;show_array($data, $textlimit);
	} elsif ($type eq 'HASH') {
		return $o-&gt;show_hash($data, $textlimit);
	} elsif ($type eq 'REF') {
		return $o-&gt;show_ref($data, $textlimit);
	}

	$o-&gt;error('Unexpected error.');
	return;
}

# Displays the contents of an array.
sub show_array {
	my $o=shift;
	my $data=shift;
	my $textlimit=shift;

	my $i=0;
	foreach my $item (@$data) {
		my $tt=scalar($item);
		$tt=substr($tt, 0, $textlimit).'...' if (($textlimit) &amp;&amp; (length($tt)&gt;$textlimit));
		print '  ', $i, ' =&gt; ', $tt, "\n";
	} continue {
		$i++;
	}

	$o-&gt;info('  (empty array)') if ($i==0);
	return;
}

# Displays the contents of a hash.
sub show_hash {
	my $o=shift;
	my $data=shift;
	my $textlimit=shift;

	my $i=0;
	foreach my $ky (sort keys %$data) {
		my $tt=scalar($data-&gt;{$ky});
		$tt=substr($tt, 0, $textlimit).'...' if (($textlimit) &amp;&amp; (length($tt)&gt;$textlimit));
		print '  ', $ky, ' =&gt; ', $tt, "\n";
	} continue {
		$i++;
	}

	$o-&gt;info('  (empty hash)') if ($i==0);
	return;
}

# Displays the contents of a reference.
sub show_ref {
	my $o=shift;
	my $data=shift;
	my $textlimit=shift;
	
	my $tt=scalar($$data);
	$tt=substr($tt, 0, $textlimit).'...' if (($textlimit) &amp;&amp; (length($tt)&gt;$textlimit));
	print '  ref =&gt; ', $tt, "\n";
	return;
}

# Returns the reference type.
sub type {
	my $o=shift;
	my $obj=shift;

	my $type;
	if (ref $obj) {
		$type=scalar($obj);
		$type=(($type=~/=(.*)\(/) ? $1 : ref $obj);
	}

	return $type;
}

# Prints out a colored line of text.
sub colorline {
	my $o=shift;
	my $color=shift;
	print chr(033), '[', $color, 'm', @_, chr(033), '[0m', "\n";
	return;
}

# Displays an error message.
sub error {
	my $o=shift;
	$o-&gt;colorline('31', @_);
	return;
}

# Displays a done message.
sub done {
	my $o=shift;
	$o-&gt;colorline('32', @_);
	return;
}

# Displays an info message.
sub info {
	my $o=shift;
	$o-&gt;colorline('34;1', @_);
	return;
}

=head1 NAME

storableedit.pl - Edit Perl Storable Files

=head1 SYNOPSIS

storableedit.pl PERL_STORABLE_FILE

=head1 DESCRIPTION

B&lt;storableedit.pl&gt; is a simple command line editor for Perl Storable files. Its interface is similar to a shell.

When the program is started, it reads the whole file and displays the first level of the data structure. One can then dive into the structure with the B&lt;cd&gt; command and display values with the B&lt;ls&gt; or B&lt;l&gt; commands.

The data can be modified with usual Perl expressions, where
  I&lt;$cur&gt;  is a reference to the current node
  I&lt;$data&gt; is a reference to the root node of the data

To save the data back to file and exit, type B&lt;x&gt; or B&lt;exit&gt;. To exit without saving, type B&lt;q&gt; or B&lt;quit&gt;. If you have modified the data, you can force discarding the changes with B&lt;q!&gt; or B&lt;quit!&gt;.

=head1 BUILT-IN COMMANDS

=over 4

=item cd ELEMENT

Moves into ELEMENT. If the current node is a hashref, ELEMENT must be a key. The new current node will be $cur-&gt;{'ELEMENT'}. If the current node is an arrayref, ELEMENT must be an index and $cur-&gt;[ELEMENT] becomes the new current node. If the current node is a reference to a reference, type B&lt;cd ref&gt;. Note that you can only move into new references (hashref, arrayref or ref, but not scalars).

To move up to the parent, type B&lt;cd ..&gt; (or just B&lt;..&gt;). To move up two steps, type B&lt;cd ...&gt; (or just B&lt;...&gt;).

=item ..

Shortcut for B&lt;cd ..&gt;

=item ...

Shortcut for B&lt;cd ...&gt;

=item ls

Displays the contents of the current node. For hashrefs, all key/value pairs are listed. For arrayrefs, all elements are listed.

Note that ls doesn't take any arguments, i.e. you can't use regexes to display only parts of the content.

=item l

Similar as B&lt;ls&gt;, but cuts all values that are longer than 50.

=item x, exit

Saves the (modified) data structure and quits.

=item q, quit

Quits without saving. If the data structure has been modified, a warning is shown.

=item q!, quit!

Forces quiting without saving.

=back

=head1 PERL EXPRESSIONS

If a command is not recognized as a built-in command, the whole line is passed to the Perl eval() function. Two variables are provided to access the data structure:
  I&lt;$cur&gt;  is a reference to the current node
  I&lt;$data&gt; is a reference to the root node of the data

Note that this script does not check what you are doing. It does NOT ask to confirm when you delete values. But keep in mind that you can always quit with B&lt;q!&gt; to discard all changes.

In case of syntax or runtime errors, the Perl error messages are shown.

Simple examples:

    $cur-&gt;{'foo'} = 'bar';    # if $cur is a hashref
    $cur-&gt;[0] = 'bar';        # if $cur is an arrayref
    $cur-&gt;[1] = {'a' =&gt; 'b'}; # creates new hashref
    $cur-&gt;[2] = ['a', 'b'];   # creates new arrayref

Fancy examples:

    push @$cur, 'bar';
        # adds a new value to the current arrayref

    push @$data, pop @$cur;
        # more array ops

    $cur-&gt;{'list'} = split(/,/, $cur-&gt;{'string'};   
        # splitting a string

    $cur-&gt;{'list'} = [sort values %{$cur-&gt;{'hashref'}}];
        # sorted values of a hashref

    print join("\n", grep {/abc/} keys %$cur)
        # grep, join ... it's Perl!

    $data = $cur;
        # sets the current node as new root
        # note that you might loose data ...

    $cur-&gt;{'imported'}=retrieve('otherfile.store');
        # imports from another Storable file

    store($cur, 'otherfile.store');
        # exports to another Storable file

Perl-OO examples:

    use My::Module;
        # load My::Module

    $cur-&gt;{'obj'} = My::Module-&gt;new();
        # create a new My::Module object

    $cur-&gt;{'obj'}-&gt;my_method();
        # call a method

    bless $cur, 'My::Module';
        # blessing manually

To enter multiline Perl expressions, put a backslash (\) at the end of each line. Example:

    open(my $fh, '&lt;', 'myfile.txt');\
    $cur-&gt;{'firstline'}=&lt;$fh&gt;;\
    close $fh;

=head1 CAVEATS

=over 4

=item Cyclic Structures

B&lt;storableedit.pl&gt; also handles cyclic structures.

=item File Handles 

File handles are not stored by the Storable module (for obvious reasons).

=item Objects

When loading storable files with (blessed) objects, the corresponding modules are not automatically loaded. If you need to invoke methods, type B&lt;use My::Module;&gt; or B&lt;require "/path/to/module.pm";&gt; to load the necessary module(s).

=back

=head1 AUTHORS

Thomas Lochmatter &lt;thl@lothosoft.ch&gt;.

=head1 README

A simple command line editor for Perl Storable files. The interface is similar to a shell. It allows to easily walk through the data structure of the file and to list and change values.

=begin comment

=pod PREREQUISITES

strict
Storable
Term::ReadLine

=pod OSNAMES

any

=pod SCRIPT CATEGORIES

Unix/System_administration

=end comment

=cut
</pre></body></html>