Skip to content

Instantly share code, notes, and snippets.

@xtetsuji
Last active August 21, 2017 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xtetsuji/af8ba0fcabcf62b56ae9855881ea6ff3 to your computer and use it in GitHub Desktop.
Save xtetsuji/af8ba0fcabcf62b56ae9855881ea6ff3 to your computer and use it in GitHub Desktop.
days_ago subroutine sample. confirmation number of arguments for safety.
#!/usr/bin/perl
use strict;
use warnings;
sub days_ago {
# 1引数か2引数かを厳密に見る
my ($time, $n);
if ( @_ == 1 ) {
$time = shift;
$n = 1;
} elsif ( @_ == 2 ) {
# 2引数なのに $n が undef の場合はエラー
# 別の場所から取得したつもりの引数 $n が実は undef だった場合に、それをサブルーチン内で 1 とすることはバグの温床となるから
$time = shift;
$n = shift;
if ( !defined $n || $n =~ /\D/ ) {
die "2nd argument is required as digit if it is given.\n";
}
} else {
die "argument error";
}
my $days_ago_time = $time - 86400 * $n;
return wantarray ? localtime($days_ago_time) : $days_ago_time;
}
__END__
2引数で呼び出すとき、外部から取得した値が未定義かどうか気にせず入れると、思わぬことになる場合がある
my $day = query_day(); # 数字もしくは未定義
my $days_ago_time = days_ago(time, $day);
この場合、未定義の場合に「1日前」を返すことは多くの場合において意図しないことが起こるはずなので
days_ago サブルーチン内で @_ の要素数を確認する必要が出てくる。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment