Dir.pm

The package Tree::Prefix::Dir handles the prefix tree in the format of a directory structure.

This is the documentation of all downloads.

Move your mouse over the code area and look at its top right corner where a set of icons for downloading, copy-pasting, etc. will appear.


#!/usr/bin/perl
package Tree::Prefix::Dir;

use strict;
use warnings;

sub new {
	my $classname=shift;

	my $self={};
	$self->{list_file}="ls.txt";

	bless($self);
	return $self;
}

# ============ set directory to save prefix tree to ============
sub set_basedir {
	my $self=shift;
	my $basedir=shift;

	if (! -d $basedir) {
		mkdir $basedir;
	}

	$self->{basedir}=$basedir;
	chdir $self->{basedir};
}

# ============ insert word to prefix tree as sequence of letters - relative path (prefix) from the root ============
sub insert_dir {
	my $self=shift;
	my $dir=shift;

	my @letters=split//, $dir;
	chdir $self->{basedir};

	for my $letter (@letters) {
		if (! -d $letter) {
			mkdir $letter;

		}
		chdir $letter;
	}
}

# ============ changes directory in prefix tree - relative path (prefix) from the root ============
sub change_dir {
	my $self=shift;
	my $dir=shift;

	my @letters=split//, $dir;
	chdir $self->{basedir};

	for my $letter (@letters) {
		if (-e $letter) {
			chdir $letter;
		} else {
			# fail to change dir - but list_files() will filter further based on prefix
		}
	}

	return "";
}

# ============ insert list into a specified node of the tree ============
sub insert_files {
	my $self=shift;

	my $dir=shift;
	my $files=shift;

	$self->change_dir($dir);

	open OUT, ">$self->{list_file}";
	print OUT join "\n", sort @$files;
	close OUT;
}

# ============ delete files of specified node of the tree ============
sub delete_files {
	my $self=shift;
	my $dir=shift;

	$self->change_dir($dir);

	if (-e $self->{list_file}) {
		unlink $self->{list_file};
	}
}

# ============ lists all the subdirectories of a specified node ============
sub list_dir {
	my $self=shift;
	my $dir=shift;

	$self->change_dir($dir);
	my @list=split/\n/, `ls`;
	@list=grep { $_ ne $self->{list_file} } @list;

	return \@list;
}

# ============ check whether selected directory was already processed ============
sub exists_file {
	my $self=shift;
	my $dir=shift;

	$self->change_dir($dir);
	return -e $self->{list_file};
}

# ============ lists all the files of a specified node ============
sub list_files {
	my $self=shift;
	my $dir=shift;

	my @list=();
	$self->change_dir($dir);

	if (-e $self->{list_file}) {
		open IN, "<$self->{list_file}";
		@list=<IN>;
		close IN;

		my $quote_dir=quotemeta $dir;
		@list=grep { /^$quote_dir/i } map { chomp $_; $_ } @list;
	}

	return \@list;
}

1;