Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

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 (Cardinal) on Oct 14, 2019 at 16:17 UTC
    > Why does it do that?

    readline in list context.


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

    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 (Prior) 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.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2020-10-27 18:38 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (257 votes). Check out past polls.