Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

print source golf

by Anonymous Monk
on Oct 14, 2019 at 16:02 UTC ( #11107426=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I was golfing around with ways to make perl print its own source and came up with something odd. I would expect the following program to print the first line of itself but it prints the entire file. Why does it do that?
#!/usr/bin/perl use strict; use warnings; print do{@ARGV=$0;<>};
My path thru this course:
print do{local(@ARGV,$/)=$0;<>}; # the usual idiom print do{@ARGV=$0;local$/;<>}; print do{@ARGV=$0;$/='';<>}; # bad print do{open$_,"<$0";<$_>}; print do{@ARGV=$0;*/;<>}; # wtf print do{@ARGV=$0;<>}; # wow

Replies are listed 'Best First'.
Re: print source golf
by LanX (Archbishop) on Oct 14, 2019 at 16:17 UTC
    > Why does it do that?

    readline in list context.

    FWIW

    use strict; use warnings; seek DATA,0,0; print scalar <DATA>; __DATA__
    prints

    use strict;

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re: print source golf
by Corion (Pope) on Oct 14, 2019 at 16:21 UTC

    How about this?

    #!perl open 0;print for<0>;

    This takes advantage of

    • Single-argument open opens a filehandle *X using the value stored in $X as the filename. Since $0 contains the filename of our program, *0 will be opened as our filehandle.

    • print for<0>; reads from filehandle *0 and prints the content.
Re: print source golf
by tybalt89 (Parson) on Oct 14, 2019 at 16:07 UTC
Re: print source golf
by daxim (Curate) on Oct 14, 2019 at 17:24 UTC
    print do{@ARGV=$0;*/;<>}; # wtf
    */ is the glob for the family of variables named /, short for *main::/.

    Perl core uses $/. Regexp::Grammars uses %/.

Re: print source golf
by davido (Cardinal) on Oct 15, 2019 at 15:43 UTC

    Is it cheating to use the shell?

    #!/usr/bin/perl exec"cat $0"

    If you're ok with letting the output happen on STDERR instead of STDOUT:

    #!/usr/bin/perl die`cat $0`

    ...which shaves off one keystroke.


    Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11107426]
Front-paged by haukex
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2019-12-15 02:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?