looks_like_numer(Scalar::Util)で数字を判定する

1
2
3
4
5
6
7
8
#!/usr/bin/env perl
use strict;
use warnings;

my $x;
my $y;

print $x - $y;
1
2
3
Use of uninitialized value $y in subtraction (-) at warnings.pl line 8.
Use of uninitialized value $x in subtraction (-) at warnings.pl line 8.
0
1
2
3
4
5
6
7
8
#!/usr/bin/env perl
use strict;
use warnings;

my $x;
my $y = '1e';

print $x - $y;
1
2
3
Argument "1e" isn't numeric in subtraction (-) at warnings.pl line 8.
Use of uninitialized value $x in subtraction (-) at warnings.pl line 8.
-1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env perl
use strict;
use warnings;
use Scalar::Util qw(looks_like_number);

my $x;
while (1) {
  print "数値を入力してください >>> ";
  $x = <STDIN>;
  chomp $x;
  last if want_number($x);
}
print qq{入力された数値は `$x` です};
exit;

sub want_number {
  my ($args) = @_;
  return 1 if looks_like_number($args);
  print "エラー:数値ではありません!\n";
  return;
}
comments powered by Disqus
Built with Hugo
テーマ StackJimmy によって設計されています。