Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: syntax questions

by rjt (Deacon)
on Mar 07, 2013 at 01:49 UTC ( #1022130=note: print w/ replies, xml ) Need Help??


in reply to syntax questions

While my esteemed predecessors have done a good job of answering your direct questions, perhaps I can shed some light on a few stylistic questions you didn't ask, but may still find informative.

The line:

     open FILELIST, ">$filelist";

is problematic for a couple of reasons:

  • The open might fail (for example, if the file does not exist), so you need to check the return.
  • The two-argument open (with the append (>) symbol in the same string as the filename) is a potential security risk; see the old Two-arg open() considered dangerous discussion for more info.
  • The filehandle, FILELIST, is in the global symbol table. It's better form to create a lexical variable instead with my.

So, instead, I would write:

(UPDATED thanks to AnomylousMonk's good catch of a very carelessly chosen variable name)

open my $fh, '>', $filelist or die "Can't open $filelist: $!";

If it fails, the program will exit with an informative error code. You could instead wrap the open call in an if statement if you want to do something else.

Purely personal preference on this next one, but your entire foreach { ... } loop could be more concisely written:

    print $fh $_ for @files;


Comment on Re: syntax questions
Select or Download Code
Re^2: syntax questions
by AnomalousMonk (Monsignor) on Mar 07, 2013 at 03:28 UTC
    open my $filelist, '>', $filelist or die "Can't open $filelist: $!";

    This is simply an inadvertance, but using a new lexical  my $filelist for the filehandle in the open statement masks the file name in the old lexical of the same name (and also generates a warning if warnings are enabled, which is strongly recommended). I would write something like:

    >perl -wMstrict -le "my $filelist = 'xyzzy'; open my $filehandle, '>', $filelist or die qq{opening '$filelist': $! +}; print $filehandle $_ for qw(foo bar baz); close $filehandle or die qq{closing '$filelist': $!}; " >type xyzzy foo bar baz

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2014-08-23 02:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (171 votes), past polls