in reply to STDIN typeglob
One of the benefits of writing tests (and particularly of TDD) is that it can give you a signal about your interface: if something is difficult to write tests for, maybe it's the interface that should change.
A module providing a function that reads from STDIN would be an example of that: perhaps it would be easier to test, _and_ provide a more powerful, flexible function if the function were to accept the filehandle to read from as an argument instead.
A typical way to use such a function to read from STDIN would be to pass a reference to the glob:
MyModule::function(\*STDIN);Typeglobs aren't really a "legacy left over from the days before Perl had references", rather they expose aspects of how Perl works internally. The introduction of references certainly reduced the number of situations where one needs to use globs, but because filehandles and directory handles don't have their own sigil to address them directly (the way $STDIN, @STDIN, %STDIN, &STDIN do), a glob reference as in the example above is still a perfectly fine way to access them.
Another example is for getting clever with generated code, for example to auto-generate accessors for an object:
for my $accessor (qw{ foo bar }) { my $method = sub { my($self) = @_; return $self->{$accessor}; }; # inject it as a named subroutine no strict 'refs'; *$accessor = $method; }
This works due to one of the "magic" aspects of globs: if you assign a reference to a glob, it will store the thing referenced in the appropriate slot. In this case we are assigning a subroutine reference, so that loops creates subroutines "foo" and "bar" (almost) exactly as if we had defined them in the normal way like:
sub foo { my($self) = @_; return $self->{foo}; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: STDIN typeglob
by afoken (Chancellor) on Jun 12, 2023 at 09:35 UTC | |
by eyepopslikeamosquito (Archbishop) on Jun 12, 2023 at 13:17 UTC | |
by afoken (Chancellor) on Jun 12, 2023 at 19:53 UTC | |
by Bod (Parson) on Jun 13, 2023 at 20:42 UTC | |
by Bod (Parson) on Jun 13, 2023 at 20:58 UTC | |
by eyepopslikeamosquito (Archbishop) on Jun 14, 2023 at 00:24 UTC | |
by Bod (Parson) on Jun 18, 2023 at 17:13 UTC | |
Re^2: STDIN typeglob
by Bod (Parson) on Jun 11, 2023 at 21:48 UTC | |
by hippo (Archbishop) on Jun 11, 2023 at 22:07 UTC |