kiz has asked for the wisdom of the Perl Monks concerning the following question:

Does <STDIN>, in scalar context, always return a value in string mode? My testing seems to show that $foo = 077 is 63 in decimal and $foo = "077" is 77 decimal - which is quite sensible, however $foo = <STDIN> (where 077 is entered) also returns 77, not 63. Is <STDIN> always string mode?


-- Ian Stuart
A man depriving some poor village, somewhere, of a first-class idiot.

Replies are listed 'Best First'.
Re: <STDIN> always in string mode?
by Ido (Hermit) on Mar 27, 2006 at 13:10 UTC
    If this is the specific case you're handling, please don't use eval, use oct() instead:
    $val=<STDIN>; $val = oct($val) if $val =~ /^0/;
    Or something like that...
Re: <STDIN> always in string mode?
by rinceWind (Monsignor) on Mar 27, 2006 at 11:10 UTC

    Reads from a file handle using the diamond (<>) operator will always pass you a string - such is the nature of a read.

    Treating 077 as octal is something perl's parsing does at compile time. If you want this at run time, you need to eval:

    my $foo = "077"; print eval($foo), "\n"; # prints 63

    --

    Oh Lord, won’t you burn me a Knoppix CD ?
    My friends all rate Windows, I must disagree.
    Your powers of persuasion will set them all free,
    So oh Lord, won’t you burn me a Knoppix CD ?
    (Missquoting Janis Joplin)

Re: <STDIN> always in string mode?
by kiz (Monk) on Mar 27, 2006 at 11:12 UTC
    Further tests have shown that you can "anonymise"(sp?) the scalar with an eval:
    perl -e '$foo=<STDIN>;$foo=eval($foo);print(($foo*2)."\n")'


    -- Ian Stuart
    A man depriving some poor village, somewhere, of a first-class idiot.
      be aware that evaling something read from an external file or STDIN is highly insecure. In an untrusted environment, you should check the input (and use taint checking):
      $foo = <STDIN>; if ($foo =~ /^(\d*)$/) { $foo = eval $1; print "foo: $foo\n" } else { die "bad input" }