On Dec 31, 2007 2:45 AM, Prabu Ayyappan <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> What is the difference in Accepting the following form of standard input?
>
> 1) $a = <STDIN>;
> 2) $b = <stdin>;
> 3) $c = <>;
>
> Now check,
> print $a $b $c;
>
>
> What is actually happening?

The first two are the same thing (but you should use STDIN for
consistency's sake).  The third is similar, but does some magic things
as well.  If there are entries in @ARGV (the variable that holds what
was passed on the command line) it will treat those entries as file
names and attempt to open and read from them (setting $ARGV to the
current file being read).  If there is nothing in @ARGV, it will use
the STDIN.  This mimics the normal filter-style-program from UNIX
(e.g. grep, wc, sort, etc).  For instance, this is a primitive version
of grep:

#!/usr/bin/perl

use strict;
use warnings;

die "$0 needs a pattern to match with" unless @ARGV;

#remove the pattern from @ARGV
my $pattern_string = shift;

#compile the pattern
#WARNING: this is bad, we should check that
#$pattern_string does not use any of the
#forms that allow execution of code
#before compiling it
my $pattern = qr/$pattern_string/;

#if there is more than one file to grep
#then print the file name and the line
my $print_filename = @ARGV > 1;

#loop over each line from STDIN or the files in @ARGV
#print the lines that match the pattern
while (<>) {
        if (/$pattern/) {
                print "$ARGV:" if $print_filename;
                print;
        }
}

and here is hot it is used:

[EMAIL PROTECTED]:~$ perl grep.pl perl grep.pl
#!/usr/bin/perl
[EMAIL PROTECTED]:~$ cat grep.pl | perl grep.pl print
#then print the file name and the line
my $print_filename = @ARGV > 1;
#print the lines that match the pattern
                print "$ARGV:" if $print_filename;
                print;
[EMAIL PROTECTED]:~$ perl grep.pl perl grep.pl bench.pl
grep.pl:#!/usr/bin/perl
bench.pl:#!/usr/local/ActivePerl-5.10/bin/perl

Compare that output with the output of the real grep in similar situations:

[EMAIL PROTECTED]:~$ grep perl grep.pl
#!/usr/bin/perl
[EMAIL PROTECTED]:~$ cat grep.pl | grep print
#then print the file name and the line
my $print_filename = @ARGV > 1;
#print the lines that match the pattern
                print "$ARGV:" if $print_filename;
                print;
[EMAIL PROTECTED]:~$ grep perl grep.pl bench.pl
grep.pl:#!/usr/bin/perl
bench.pl:#!/usr/local/ActivePerl-5.10/bin/perl

snip
> Will this be written to some standard input file?
snip

STDIN is the "standard input file handle", it is attached to fileno 0
by default.

snip
> If so In windows where this will be written?
snip

If you are asking where the print is written (since it is the only
write you show), it is written to STDOUT file (fileno 1 by default).

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to