CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Strange line behavior

 



dcodelli
Deleted

Mar 15, 2000, 8:37 AM

Post #1 of 5 (655 views)
Strange line behavior Can't Post

I have the following program, followed by an input file, postinput. I would expect this program to print the first three lines,

apple
cherry
banana

but instead it prints the whole file. Could someone tell me why? I'm running Active Perl, version 5.005_03 built for MSWin32-x86-object


$fname = "postinput";
$ofname = "postoutput";
open FH, $fname or die $!;
open OFH, ">$ofname" or die $!;

for ($i = 0 ; $i < 3 ; ++$i)
{

print OFH <FH>;

}

input file:
apple
cherry
banana
orange
strawberry




Cure
User

Mar 15, 2000, 1:40 PM

Post #2 of 5 (655 views)
Re: Strange line behavior [In reply to] Can't Post

Hi

This would do what you were expecting:

$fname = "postinput.txt";
$ofname = "postoutput.txt";
open (OLD, "<$fname") or die "$!";
open (NEW, ">$ofname") or die "$!";

while (<OLD> )
{
print NEW if $.<4;
}

close(OLD);
close(NEW);


Cure



japhy
Enthusiast

Mar 15, 2000, 10:45 PM

Post #3 of 5 (655 views)
Re: Strange line behavior [In reply to] Can't Post

The reason yours didn't work as you expect is because the readline(FH) function (also usable as the <FH> operator) returns one line in scalar context, but the rest of the lines until end-of-file in list context.

"Context?"

print() takes a list. This means that saying

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


print localtime;
# and
$date = localtime;
print $date;
</pre><HR></BLOCKQUOTE>

print two different things. localtime(), in list context, returns a list of numbers. In scalar context, it returns a string that is a human-readable date. localtime(), like <>, does different things in scalar and list context.

If you want to force scalar context, use the scalar() function:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


print scalar <FILE>;
</pre><HR></BLOCKQUOTE>

To read more about context, read http://www.pobox.com/~japhy/articles/pm/2000-02.html ("List" is a Four-Letter Word).


dcodelli
Deleted

Mar 16, 2000, 5:13 AM

Post #4 of 5 (655 views)
Re: Strange line behavior [In reply to] Can't Post

Thanks. I see how yours works, but I'm still not sure why mine didn't.

David


BillKSmith
Veteran

Mar 3, 2011, 12:22 PM

Post #5 of 5 (521 views)
Re: [dcodelli] Strange line behavior [In reply to] Can't Post


Code
$fname = "postinput";  
$ofname = "postoutput";
open FH, $fname or die $!;
open OFH, ">$ofname" or die $!;

for ($i = 0 ; $i < 3 ; ++$i)
{

print OFH scalar <FH>;

}

Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives