perl - Operator to read a file using file handle -


i trying read file,

    while($line = $file_handle) 

when ran code, program hung.

i noticed read file using file handle, need used <>

   while($line = <file_handle>) 

the later code ran.

now know operator <> read file line line, want know happening when dont provide <> operator? not able find end of line ?or?

thankyou

short   file read <> operator without it assignment, infinite loop.


the while (...) { ... } checks condition inside () , if true executes body in block {}. keeps doing until condition in () evaluates understood false (generally 0, '0', '', or undef). operator <> provides, example, have idiom

while (my $line = <$file_handle>) { ... } 

the <> operator reads line @ each iteration resource $file_handle associated , when reaches end-of-file returns undef loop terminates , program execution continues @ next statement after loop. diamond operator <> operator form function readline. see i/o operators in perlop. work $file_handle has valid resource can retrieve data.

without <> operator nothing read anywhere, there assignment. code following. copies variable $file_handle variable $line. return value of operation in perl value ends in $line, , if 'truthy' value body { ... } executed. $file_handle evaluates 'true', otherwise loop body not execute once , program continue. $line true, too. if $file_handle doesn't change in body {...} of loop condition true.

then whatever in body keeps being executed, without reason loop terminate, , never returns control program. it's infinite loop, , program appears hang.


note used deliberately , may see code like

while (1) {     # compute needed     # recalculate condition when stop     last if $condition_to_terminate; } 

this approach can risky though, since condition can more , more complicated , error sneak in, in case end infinite loop. there clearer ways control loops.

a different example event loop, crucial enter infinite loop can wait event of sort, @ point particular action taken. how gui's work, example, , number of other systems.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo