From: Robert 'phaylon' Sedlacek Date: Wed, 9 May 2012 23:12:20 +0000 (+0000) Subject: more I/O utils X-Git-Tag: v0.001_001~96 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=db5ba31ffa3a13279b863257a8ef35bfcfb9968b;p=scpubgit%2FSystem-Introspector.git more I/O utils --- diff --git a/lib/System/Introspector/Util.pm b/lib/System/Introspector/Util.pm index f9c9d85..f2a7555 100644 --- a/lib/System/Introspector/Util.pm +++ b/lib/System/Introspector/Util.pm @@ -2,12 +2,30 @@ use strictures 1; package System::Introspector::Util; use Exporter 'import'; +use IPC::Run qw( run ); our @EXPORT_OK = qw( handle_from_command + handle_from_file + files_from_dir + output_from_command + output_from_file transform_exceptions ); +sub files_from_dir { + my ($dir) = @_; + my $dh; + opendir $dh, $dir + or die "Unable to read directory $dir: $!\n"; + my @files; + while (defined( my $item = readdir $dh )) { + next if -d "$dir/$item"; + push @files, $item; + } + return @files; +} + sub transform_exceptions (&) { my ($code) = @_; local $@; @@ -17,6 +35,21 @@ sub transform_exceptions (&) { return $result; } +sub output_from_command { + my ($command, $in) = @_; + $in = '' + unless defined $in; + my ($out, $err) = ('', ''); + my $ok = run($command, \$in, \$out, \$err); + return $out, $err, $ok + if wantarray; + $command = join ' ', @$command + if ref $command; + die "Error running command ($command): $err\n" + unless $ok; + return $out; +} + sub handle_from_command { my ($command) = @_; open my $pipe, '-|', $command @@ -24,4 +57,19 @@ sub handle_from_command { return $pipe; } +sub handle_from_file { + my ($file) = @_; + open my $fh, '<', $file + or die "Unable to read $file: $!\n"; + return $fh; +} + +sub output_from_file { + my ($file) = @_; + my $fh = handle_from_file $file; + return <$fh> + if wantarray; + return do { local $/; <$fh> }; +} + 1;