environment and i/o
スクリプト言語の比較
http://hyperpolyglot.org/scripting を参考に、スクリプト言語の勉強をしてまいります。
environment and i/o
perl | php | python | ruby | |
---|---|---|---|---|
external command |
system('ls');
|
<?php exec('ls'); ?>
|
import os os.system('ls')
|
system('ls')
|
backticks |
`ls`;
|
<?php exec('ls', $out = array()); $out ?>
|
import os os.popen('ls').read()
|
`ls`
|
command line args, script name |
$#ARGV + 1 $ARGV[0] $ARGV[1] 0
|
<?php count($argv) $argv[0] $argv[1] $_SERVER["SCRIPT_NAME"] ?>
|
import sys len(sys.argv)-1 sys.argv[1] sys.argv[2] sys.argv[0]
|
ARGV.size ARGV[0] ARGV[1] 0
|
print to standard out |
print "hi world\n";
|
<?php echo "hi world\n"; ?>
|
print("hi world")
|
puts "hi world"
|
standard file handles |
STDIN STDOUT STDERR
|
<?php $stdin = fopen('php://stdin','r'); $stdout = fopen('php://stdout','w'); $stderr = fopen('php://stderr','w'); ?>
|
import sys
sys.stdin sys.stdout sys.stderr
|
$stdin $stdout $stderr
|
open file |
open FILE, '/etc/hosts';
|
<?php $f = fopen('/etc/hosts','r'); ?>
|
f = open('/etc/hosts')
|
f = File.open('/etc/hosts') or File.open('/etc/hosts') { |f|
|
open file for writing |
open FILE, ">/tmp/perl_test";
|
<?php $f = fopen('/tmp/php_test','w'); ?>
|
f = open('/tmp/test','w')
|
f = File.open('/tmp/test','w') or File.open('/tmp/test','w') { |f|
|
close file |
close FILE;
|
<?php fclose($f); ?>
|
f.close()
|
f.close
|
read line |
$line = <FILE>
|
<?php $line = fgets($f); ?>
|
f.readline()
|
f.gets
|
iterate over a file by line |
while ($line = <FILE>) {
|
<?php while (!feof($f)) { $line = fgets($f); ?>
|
for line in f:
|
f.each do |line|
|
chomp |
chomp $line;
|
<?php chop($line); ?>
|
line = line.rstrip('\r\n')
|
line.chomp!
|
read entire file into array or string |
@a = <FILE>; $/ = undef; $s = <FILE>;
|
<?php $a = file('/etc/hosts'); $s = file_get_contents('/etc/hosts'); ?>
|
a = f.readlines() s = f.read()
|
a = f.lines.to_a s = f.read
|
write to file |
print FILE "hello";
|
<?php fwrite($f, 'hello'); ?>
|
f.write('hello')
|
f.write('hello')
|
flush file |
use IO::Handle;
FILE->flush();
|
<?php ?>
|
f.flush()
|
f.flush
|
environment variable |
$ENV{'HOME'}
|
<?php getenv('HOME') ?>
|
import os os.getenv('HOME')
|
ENV['HOME']
|
exit |
exit 0;
|
<?php exit 0; ?>
|
import sys sys.exit(0)
|
exit(0)
|
set signal handller |
$SIG{INT} = sub { die "exiting \n"; };
|
<?php ?>
|
import signal def handler(signo, frame): print("exiting ") exit -1 signal.signal(signal.SIGINT, handler)
|
Signal.trap("INT", lambda { |signo| puts "exiting "; exit })
|