execution control

スクリプト言語の比較

http://hyperpolyglot.org/scripting を参考に、スクリプト言語の勉強をしてまいります。

execution control



































































  perl php python ruby
if

if ( 0 == $n ) {
  print "no hits\n"
} elsif ( 1 == $n ) {
  print "1 hit\n"
} else {
  print "$n hits\n"
}

<?php
if ( 0 == $n ) {
  echo "no hits\n";
} elseif ( 1 == $n ) {
  echo "one hit\n";
} else {
  echo "$n hits\n";
}
?>

if 0 == n:
  print("no hits")
elif 1 == n:
  print("1 hit")
else:
  print(str(n) + " hits")

if n == 0
  puts "no hits"
elsif 1 == n
  puts "1 hit"
else
  puts "#{n} hits"
end

while

while ( $i < 100 ) { $i++ }

<?php
while ( $i < 100 ) { $i++; }
?>

while i < 100:
  i += 1

while i < 100 do
  i += 1
end

break/continue/redo

last next redo

<?php
break continue none
?>

break continue none

break next redo

for

for ( $i=0; $i <= 10; $i++ ) {
  print "$i\n";
}

<?php
for ($i = 1; $i <= 10; $i++) {
  echo "$i\n";
}
?>



none


none
range iteration

for $i (1..10) { print "$i\n" }

<?php
foreach (range(1,10) as $i) {
  echo "$i\n";
}
?>

for i in range(1,11):
  print(i)

(1..10).each { |i| puts i }

statement modifiers

print "positive\n" if $i > 0;
print "nonzero\n" unless $i == 0;



none


none

puts 'positive' if i > 0
puts 'nonzero' unless i == 0

raise exception

die "bad arg";

<?php
throw new Exception("bad arg");
?>

raise Exception("bad arg")

# raises RuntimeError
raise "bad arg"

catch exception

eval { risky };
if ($@) {
  print "risky failed: $@\n";
}

<?php
try {
  risky();
} catch (Exception $e) {
  echo 'risky failed: ',
    $e->getMessage(), "\n";
}
?>

try:
  risky()
except:
  print("risky failed")

# catches StandardError
begin
  risky
rescue
  print "risky failed: "
  puts $!.message
end

global variable for last exception raised

$EVAL_ERROR: $@
$OS_ERROR: $!
$CHILD_ERROR: $?


none


none


last exception: $!
backtrace array of exc.: $@
exit status of child: $?
define exception

none

<?php
class Bam extends Exception {
  function __construct() {
    parent::__construct("bam!");
  }
}
?>

class Bam(Exception):
  def __init__(self):
    super(Bam, self).__init__("bam!")

class Bam < Exception
  def initialize
    super("bam!")
  end
end

catch exception by type and assign to variable

none

<?php
try {
  throw new Bam;
} catch (Bam $e) {
  echo $e->getMessage(), "\n";
}
?>

try:
  raise Bam()
except Bam as e:
  print(e)

begin
  raise Bam.new
rescue Bam => e
  puts e.message
end

finally/ensure

none


none

try:
  acquire_resource()
  risky()
finally:
  release_resource()

begin
  acquire_resource
  risky
ensure
  release_resource
end

uncaught exception behavior

stderr and exit

<?php
?>



stderr and exit


stderr and exit
start thread

use threads;
$f = sub { sleep 10 };
$t = threads->new($f);



none

class sleep10(threading.Thread):
  def run(self):
    time.sleep(10)
t = sleep10()
t.start()

t = Thread.new { sleep 10 }

wait on thread

$t->join;



none

t.join()

t.join