Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^3: Issue splitting in while Loop

by GrandFather (Saint)
on Jul 30, 2011 at 04:04 UTC ( [id://917590]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Issue splitting in while Loop
in thread Issue splitting in while Loop

This is an issue that comes up a lot. Perl inherits a lot of syntax and style from C and various other languages so some of the conventions used in older Perl derive from what was required in other languages. However Perl has moved on and there are now often clearer and safer ways of doing things. As mentioned in my previous reply there are several issues related to using old school two parameter open and bare word style file handle identifiers (IN in your example). There are two main issues with using bare word file handles: it is easy to mistype them and introduce subtle and hard to find bugs, and bare word file handles have global scope.

The typo issue should be fairly obvious. The global scope thing is less so and understanding depends on understanding the difference between package variables and lexical variables. Lexical variables are the ones you introduce using my and they are pretty much limited to the block they are introduced in. For a file handle that means that the file is closed for you when processing exits the block containing the lexical variable. Consider:

for my $fileIdx (1 .. 10) { my $logName = "log$fileIdx.txt"; open my $logOut, '>', $logName or die "Can't create $logName: $!\ +n"; ... }

which creates 10 log files. Notice that a close isn't needed because $logOut goes out of scope at the closing } and Perl closes the file for you.

The three parameter open issue is also two fold. The first thing is that two parameter open defaults to input so it is fairly easy to forget that you need to provide the > to specify output - somehow that is a really hard bug to spot! The second, and more subtle issue is that a user supplied file name can run a command supplied by the user by appending a pipe ('|') character to the command and presenting that as the file name.

Note by the way that the file name is not the file handle. open creates a file handle using the file name and mode information. The file handle is just the way the functions which deal with the file for I/O know which file to manipulate and what operations are OK.

True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://917590]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-03-28 08:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found