Some handy Perl commands that is not used as much.
Use ‘-’ to refer to STDOUT & STDIN.
open(INP, ‘-’) —> STDIN
open(OUT, ‘>-) —> STDOUT
$fh = IO::File->new(‘-’,'w’) —> STDOUT
Following the filehandle with ‘-|’ opens the output of a shell command as a file.
open($fh, ‘-|’, ‘ls -l’);
open($fh, ‘-|’, ‘cat tmp.txt | sort’);
Similarly IO::Pipe can be used to get the same affect:
$fh = new IO::Pipe;
$fh->reader(qw(ls -l));
Then you can print the output
while (<$fh>) { print; }
Open a zipped file
open(INP, ‘-|’, ‘gunzip < tmp.txt.gz’);
Print the output of a subroutine inside a string
print “3+4 is @{ [addTwoNumbers(3,4)] }\n”;
Use IO::File to store filehandles into a hash array.
$fh{‘infile’} = IO:File->new(“tmp.txt”, “r”);
while (my $line = $fh{‘infile’}->getline) {
print $line;
}
$fh{‘infile’}->close;
Filed under: Perl | Tagged: programming, scripting, tips | Leave a Comment »