On Dec 31, 2003, at 11:57 AM, Eric Walker wrote:

OK, some how my $_ variable is out of sync  with my <> operator.
if I print out $_ I get line a of my file and if I do a my $test =
<GIN>, and print out $test I get a different line that is more than the
next line away. example.

I am the best
you are the best
we are the best
they are the best.

print $_  "I am the best"
$test = <GIN>;
print $test "they are the best"

any suggestion on how to resync it?

I think you are pretty confused about what <> and $_ mean.


<> is the input operator, it reads one input record (often a line) each time it is used. You're examples show it with a file handle inside of it, which is where the record/line will be read from. Example:

<FILE>; # read first line of file, and do nothing with it

my $line = <FILE>; # read next line of file and store it in $line

$_ is Perl's default variable. That means that many built-ins and some operators work with the contents of $_ unless they are told to do otherwise. Example:

print; # prints to value of $_

print "Bark!\n" if m/\bDog\b/; # prints Bark! if $_ contains the word Dog

foreach (@name) {                       # loops over @names, putting one at a time in 
$_
        # ... use $_ here to access current name
}

chomp; # removes input record separator from $_

Now where I think you are getting confused is the typical Perl idiom:

while (<FILE>) {

}

That's actually a shorthand way to write:

while ( defined( $_ = <FILE> ) ) {

}

Notice that the record/line read from FILE there is assigned to $_, making it convenient to work with the current line.

However, outside this special case $_ and <> are not related. Something like:

<FILE>; # does NOT assign to $_, line is discarded

my $line = <FILE>; # assigns to $line, $_ is untouched

Now if you want to put something in $_, you can of course:

$_ = <FILE>; # assigns next record/line to $_

Hope that clears things up for you.

James


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




Reply via email to