Utils.pm 2.45 KB
package Utils;
use strict;
use vars qw(@ISA @EXPORT);
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(fill_hash_from_array  fill_array_from_dir fill_array_from_file fill_hash_from_file fill_file_from_array); 

#-----------------------------------------------------
# Author : Emmanuel FERREIRA  (v.2)
# Contact: emmanuel.ferreira0194@gmail.com
# Date : 04/11/11
# Brief : this file provide a curly library utilities
#-----------------------------------------------------

#---------------------------------------------------------------
# SUBROUTINES
#---------------------------------------------------------------

#
# \brief fill a hashtable with an formatted array (each item <=> key=value)
# \param arrayRef the array reference
# \param hashRef the hashtable reference
#
sub fill_hash_from_array
{
	my ($arrayRef, $hashRef)=@_;

	foreach my $line (@$arrayRef)
	{
		chomp($line);
		if (length($line) > 1)
		{
			$line=~/(.*)=(.*)/i;
			$hashRef->{$1}=$2;
		}
	}
}

#
# \brief fill a referenced array whith a directory content
# \param directory path
# \param file filter
# \param reference to an array
#
sub fill_array_from_dir
{
	my ($dirPath, $filter, $array) = @_;
	my $dir;
	opendir($dir, $dirPath) or die("Cannot open directory : $dirPath");
	if($filter)
	{
		@{$array} = grep( /$filter$/, readdir($dir));
	}
	else
	{
		@{$array} = readdir($dir);
	}
	closedir($dir); 
}

#
# \brief fill a referenced array whith a file content
# \param filepath
# \param content filter (regex containing items that the program must ignore)
# \param reference to an array
#
sub fill_array_from_file
{
	my($filePath, $contentFilter, $array) = @_;
	my $file;
	
	open($file, $filePath) or die("Cannot open file : $filePath");
	if($contentFilter)
	{
		@{$array} = grep(!/$contentFilter/, <$file>);
	}
	else
	{
		@{$array} = <$file>;
	}
	close($file);
}

#
# \brief fill an hashtable from a fileConten
# \param filepath
# \param sep separator
# \param reference to an hashtable
#
sub fill_hash_from_file
{
	my($filePath, $sep, $hashtable) = @_;
	my $file;
	open($file, $filePath) or die ("Cannot open file : $filePath");
	while(<$file>)
	{
		chomp;
		my @values = split(/$sep/);
		${$hashtable}{$values[0]} = $values[1];
	}
	close($file);
}

#
# \brief fill a file with an array
# \param filepath
# \param reference to an array
#
sub fill_file_from_array
{
	my ($filePath, @array) = @_;
	my $file;
	open($file, ">$filePath") or die ("Cannot open file : $filePath");
	foreach(@array)
	{
		print $file $_;
	}
	close($file);
}
1;