use strict;
use FileHandle;
my $output_file = "/tmp/output_perl.txt";
if(my $fh = new FileHandle('> '.$output_file) ){
print $fh "Hello World!\n\nAdditional line\n";
$fh->close();
}
else{
die("Failed to write to ".$output_file);
}
if(my $fh = new FileHandle($output_file) ){
my $cnt = 0;
while(<$fh>){
print $_;
$cnt++;
}
$fh->close();
print $cnt."\n";
}
Python
import sys
output_file = "/tmp/output_python.txt"
try:
with open(output_file, "w") as wfh:
wfh.write("Hello World!\n\nAdditional line\n")
except IOError:
print("Failed to write to " + output_file)
sys.exit(1)
except:
print("Unexpected error:", sys.exc_info()[0])
sys.exit(1)
line_cnt = 0
with open(output_file, "r") as rfh:
for line in rfh:
print(line.rstrip("\n"))
line_cnt += 1
print(line_cnt)
Ruby
output_file = "/tmp/output_ruby.txt"
begin
File.open(output_file, "w") do |wfh|
wfh.puts("Hello World!\n\nAdditional line\n")
end
rescue SystemCallError => e
puts "class=#{e.class},message=#{e.message}"
rescue IOError => e
puts "class=#{e.class},message=#{e.message}"
end
line_cnt = 0
File.open(output_file, "r") do |rfh|
while (line = rfh.gets)
puts line
line_cnt += 1
end
end
puts line_cnt
Shell
#!/bin/bash
output_file="/tmp/output_shell.txt";
echo -e -n 'Hello World!\n\nAdditional line\n' > $output_file || exit 1;
line_cnt=0;
while IFS= read -r line
do
echo "$line"
line_cnt=$((line_cnt + 1))
done <"$output_file"
echo $line_cnt;
プログラミング言語比較サイトProgrammingLang.comでは、同じ問題を複数のプログラミング言語がそれぞれどのような記述で解決できるのかの例を提供。
複数の言語を比較し、貴方の問題を解決するのに最適な言語の選択と、その言語での解法を得る事を手助けします。
全問題カバー: JavaScript Perl PHP Python Ruby | 一部: C C# C++ Go Java Rust Shell
You can find programming examples to solve same problem using multiple programming languages.
Please find best programming language for your problems and solution.
Covering all cases: JavaScript Perl PHP Python Ruby | Covering some cases: C C++ C# Go Java Rust Shell