What is the difference between <stdin> and <STDIN>?
Asked Answered
A

2

17

When I use <stdin> in Perl module (*.pm) files it's not reading input from the keyboard, but when I use <STDIN> in the same place it works fine.

Why is it not getting input when I use <stdin>?

Adrianneadriano answered 2/7, 2015 at 13:2 Comment(1)
stdin: Gotta love undocumented features. Stick with STDINBerchtesgaden
V
22

STDIN is the documented filehandle. There exists stdin as well, which is aliased to STDIN, but it only works in the main:: package: main::stdin is the same as main::STDIN (as documented in perlop - Perl operators and precedence).

In a package, therefore,

package My::Package;
sub xx {
    print while <stdin>;
}

stdin is interpreted as My::Package::stdin, which doesn't exist. You can use main::stdin from a package, but using the standard STDIN (which always points to main::STDIN, even from a package) is much cleaner.

Veda answered 2/7, 2015 at 13:20 Comment(0)
K
12

Didn't know about this, but found it documented in a throw-away paragraph in perlop

The filehandles STDIN, STDOUT, and STDERR are predefined. (The filehandles stdin, stdout, and stderr will also work except in packages, where they would be interpreted as local identifiers rather than global.) Additional filehandles may be created with the open() function, amongst others. See perlopentut and "open" in perlfunc for details on this.

Kalil answered 2/7, 2015 at 13:23 Comment(5)
Why would anyone know this?Kalil
I'm actually trying to think what the point of doing it in the first place would be. I mean, I could just about see why having a lowercase alias might make some sense, but not one with different behaviour.Henequen
It's probably a historical thing that's older than packages, and no one was bothered enough to fix its behaviour when packages were introduced.Veda
Holy crup! I had learned Perl in the version 4 days I thought I was pretty conversant with the docs and sundry historical cruft, but this one is news to me...Berchtesgaden
@Veda IMHO the only sensible fix would be dropping <stdin> (which could be a compatibility problem, so let's forget it). Its only use is TMTOWTDI.Pluvious

© 2022 - 2024 — McMap. All rights reserved.