Skip to content

Instantly share code, notes, and snippets.

@sids
Created July 24, 2008 11:30
Show Gist options
  • Save sids/2122 to your computer and use it in GitHub Desktop.
Save sids/2122 to your computer and use it in GitHub Desktop.
Perl: I/O examples
http://gist.github.com/2122
Examples of I/O in Perl.
#!/usr/bin/perl
use strict; use warnings;
print STDERR "USAGE: <integer> on STDIN\nExample: 1008813135\n\n";
select STDOUT; $| = 1; # immediately flush any output
my $in = <STDIN>;
print STDOUT pack("N", int($in)), "\n";
import java.io.DataOutputStream;
public class PackTest {
public static void main (String[] args) throws Exception {
DataOutputStream out = new DataOutputStream(System.out);
out.writeInt(11351);
out.flush();
}
}
#!/usr/bin/perl
use strict; use warnings;
open my $oldout, ">&", \*STDOUT or die "Can't dup STDOUT: $!";
open OLDERR, ">&", \*STDERR or die "Can't dup STDERR: $!";
#open STDERR, '>', "foo.out" or die "Can't redirect STDOUT: $!";
open STDOUT, ">&STDERR" or die "Can't dup STDOUT: $!";
select STDERR; $| = 1; # make unbuffered
select STDOUT; $| = 1; # make unbuffered
print STDOUT "stdout 1\n"; # this works for
print STDERR "stderr 1\n"; # subprocesses too
print $oldout "stdout 2\n"; # this works for
print OLDERR "stderr 2\n"; # subprocesses too
open my $in, "<&", \*STDIN or die "Can't dup STDIN: $!";
open STDIN, "</dev/null" or die "Can't dup STDIN: $!";
my $i = <$in>;
print STDOUT $i;
$i = <STDIN>;
print STDOUT "STDIN gets nothing!\n" unless $i;
#!/usr/bin/perl
use strict; use warnings;
print STDERR "USAGE: <packed-integer> on STDIN\nExample: <!DO\n\n";
binmode STDIN, ':bytes'; # set to read bytes
read STDIN, my $bytes, 4;
print STDOUT unpack('N', $bytes), "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment