in reply to Re: Testing Input and Output
in thread Testing Input and Output

Hmm, this hangs when reading STDIN; got whatever never gets printed.

#!/usr/bin/perl use strict; use warnings; print STDOUT "stuff\n"; my $whatever = <STDIN>; print "got whatever: $whatever"; exit;

I'm not too sure why it hangs: it seems to be that STDIN actually isn't tied to STDOUT, as you think it is. For example, we can prevent the above code from hanging forever by playing with alarm:

#!/usr/bin/perl use strict; use warnings; $SIG{ALRM} = sub { die }; print STDOUT "whatever\n"; my $in; eval { alarm 1; chomp ( $in = <STDIN> ); alarm 0; }; print "got in: $in\n";
result:
whatever Use of uninitialized value in concatenation (.) or string at foo.pl li +ne 17. got in:

  1. The first line, "whatever", is us printing to STDOUT.
  2. Next we get a warning about an uninitialized value - this is the warnings pragma in action, helpfully telling us that we're trying to print something that hasn't been set yet.
  3. Finally, there's a "got in: " line where we expect to see "got in: whatever".

So - what this means is that printing to STDOUT does not automagically make data available to STDIN. And that's good, too: imagine code that looks like this:

#!/usr/bin/perl use strict; use warnings; print STDOUT "What is your name? : "; chomp ( my $name = <STDIN> ); print STDOUT "Hello, $name!\n"; exit;
Now, without running the above code, tell me: what do you expect the second print statement to print?
Yuck! Imagine if printing to STDOUT automagically made that data available to STDIN: you'd have to do some Olympian coding gymnastics to remove your STDOUT from your STDIN before you could find out what $name was entered as!

fwiw, I was confused about *why* STDOUT and STDIN aren't tied together - makes sense at first glance! - until I came up with the above code example. Hope this helps.

Update: realized greenFox was probably joking... but by golly, I learned something.

blyman
setenv EXINIT 'set noai ts=2'

Replies are listed 'Best First'.
Re: Re: Re: Testing Input and Output
by greenFox (Vicar) on Sep 04, 2002 at 01:16 UTC
    Yes I was joking and no I never meant to suggest that <STDIN> was somehow tied to <STDOUT>... glad you had some fun with it any-way :-)

    --
    Until you've lost your reputation, you never realize what a burden it was or what freedom really is. -Margaret Mitchell