more I/O utils
Robert 'phaylon' Sedlacek [Wed, 9 May 2012 23:12:20 +0000 (23:12 +0000)]
lib/System/Introspector/Util.pm

index f9c9d85..f2a7555 100644 (file)
@@ -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;