Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
given a CODE ref in a structure somewhere, how do you get the closed over values out of it?

Ok, I see what you're asking now. Whenever you want to inspect lexical variables for debugging, think PadWalker (that's also what the Perl debugger uses, as per its docs). If you wanted to get fancy, combine it with Data::Dump::Filtered and B::Deparse:

use warnings; use strict; use B::Deparse; use Data::Dump qw/dd pp/; use Data::Dump::Filtered qw/add_dump_filter/; use Sub::Util qw/subname/; use PadWalker qw/closed_over/; my $deparse = B::Deparse->new(); $deparse->ambient_pragmas(strict=>'all', warnings=>'all'); add_dump_filter(sub { my ($ctx, $obj) = @_; if ( $ctx->is_code && subname($obj)=~/\b__ANON__\z/ ) { my $vars = closed_over($obj); return { dump => 'sub '.$deparse->coderef2text($obj), comment => join("\n", map { my $v = $vars->{$_}; "my $_ = ".( ref $v eq 'ARRAY' ? pp(@$v) : ref $v eq 'HASH' ? "(".join(", ", map { pp($_).' => ' .pp($v->{$_}) } sort keys %$v ).')' : pp($$v) ).';' } sort keys %$vars ), } } return undef; }); sub x { my $i = shift; my $y = { val=>123 }; return sub { $y->{val} += $i; my $z = 2; $i *= $z; return $y; } } my $foo = { bar => x(111), }; dd $foo; dd $foo->{bar}->(); dd $foo; __END__ { bar => # my $i = 111; # my $y = { val => 123 }; sub { $y->{'val'} += $i; my $z = 2; $i *= $z; return $y; }, } { val => 234 } { bar => # my $i = 222; # my $y = { val => 234 }; sub { $y->{'val'} += $i; my $z = 2; $i *= $z; return $y; }, }
Is this the origin of the convention in Perl of writing file handle names in ALL UPPERCASE?

I don't know, but that sounds plausible. All I've found in the Camel 2nd Ed. so far is:

Since reserved words are always entirely lowercase, we recommend that you pick label and filehandle names that do not appear all in lowercase. ... Using uppercase filehandles also improves readability and protects you from conflict with future reserved words. ... if you have a package called m, s, y, or tr, then you can't use the qualified form of an identifier as a filehandle because it will be interpreted instead as a pattern match, a substitution, or a translation. Using uppercase package names avoids this problem.
This can be a legitimate concern in that you will get only a run-time error instead of a compiler error

No, you don't even get a run-time error, just a warning, which can easily be swallowed or go unnoticed if running the script from a web server, a daemon, a cron that can't send mails, a script that generates a lot of other output, and so on.

I have yet to write code that had enough bareword file handles for this to be a problem for me. ... This is probably why I have not had typo problems with them, now that I notice it.

Once again, this may apply to you, but I still don't see any good reason to suggest them to newcomers. Lexical filehandles have become the new best practice for lots of good reasons, and I think I've named pretty much all of them by now. One more might be that lexical filehandles are closed automatically when they go out of scope, but bareword filehandles are not (only when the script ends, which may be a lot later, depending on the code).

bareword file handles remain a useful tool in producing concise I/O code in a main script ...

But is that really the case? You mentioned using a filehandle named MANIFEST, and you said "Global file handles should have meaningful names." That makes sense since they're package-global, but for lexical filehandles that have limited scope, using a name like $fh is perfectly fine IMHO. open my $fh, '<', 'Manifest' or die $!; my $data = do { local $/; <$fh> }; close $fh; is 12 characters shorter than open MANIFEST, '<', 'Manifest' or die $!; my $data = do { local $/; <MAINFEST> }; close MANIFEST;, and the latter suffers from all the issues I've already named.

... while also being visually distinctive in their own way, with both ALLCAPS and different syntax highlighting from variables.

If that's really the only remaining advantage, which is strongly dependent on the editor and highlighting scheme, then I don't really see how that stacks up against all the disadvantages I named (and that you haven't responded to).

but I am suspicious of "always" and "never" in general

I know what you mean, and I feel the same way, but I don't think I said "never" anywhere in this thread. I'm a big fan of TIMTOWTDI, but also Tim Toady Bicarbonate. Don't confuse strict coding policies with best practices - the name of the latter already implies that there are other ways to accomplish the same thing, but best practices exist usually because they have advantages over the other practices, it solves issues that other methods have, and so on.

In this case, bareword filehandles are no longer the generally recommended practice in part because of the horrible debugging messes that people have had to deal with over the years of people using globals. Lexicals are simply better, which is far from saying "never use globals". But design desicions made to limit globals can also have positive effects on application architecture.

Although traditionally, Perl has often been used for scripts (I've written plenty myself, and yes, I've used "globals" in a lot of them), something that really opened my eyes is when I spent a few years coding more Java than Perl. In large applications, and especially multi-threaded ones, you just can't use globals, and for example, context objects (when properly implemented) make a ton more sense - they're thread-safe, serializable, etc. and replace the functionality that people often use globals for.

Just for example, someone coding in Mojolicious, where the production-mode server is multiprocess, may try to use globals to share information, only to find that it simply doesn't work, but someone already used to limiting the scope of their variables as much as possible will likely find it much easier to deal with - at least that's been my experience.

The concern I have is the possibility of advice that works well for a beginner, but could unintentionally limit their future growth. I am unsure exactly how "always use lexical file handles" would do that

That might be an important thing to think about, then. Given than they have so many disadvantages, other than making people aware that bareword filehandles exist, what else is there? I think it'd be enough to say something like "by the way, bareword filehandles exist and you may see them in legacy code, but nowadays the best practice is to use lexical filehandles because they have many advantages".


In reply to Re^11: Summing numbers in a file by haukex
in thread Summing numbers in a file by pvfki

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2022-05-24 13:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (82 votes). Check out past polls.

    Notices?