Search code examples
perlnumericvariable-types

Perl numeric variables


Perl and I disagree as to whether a variable is a number or not. I'm wrong, of course, but why?

my $bytes = 0;
# . . .
$bytes = $bytes + length($text);
# . . .
my $MB = $bytes / 1048576;
my $string = sprintf("Downloaded: %.1f MB\n", MB);

gives Argument "MB" isn't numeric in sprintf at foo.pl line 200..

It is, in fact, numeric as can be seen when I use

my $string = "Downloaded: $MB MB\n";

which sets the string to Downloaded: 3.09680080413818 MB.

Edit: Ah, silly mistake, thanks for catching it.


Solution

  • You need the variable sigil:

    my $bytes = 0;
    # . . .
    $bytes = $bytes + length($text);
    # . . .
    my $MB = $bytes / 1048576;
    my $string = sprintf("Downloaded: %.1f MB\n", $MB);   # <--- note the $MB at the end