Print itself
Create a program, which prints its source code to the stdout!
- Related tasks
Contents
Batch File[edit]
@echo off
for /f "tokens=*" %%s in (%~n0%~x0) do (echo %%s)
Furor[edit]
1 argv getfile dup sprint free
end
Go[edit]
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
)
func main() {
self := path.Base(os.Args[0]) + ".go"
bytes, err := ioutil.ReadFile(self)
if err != nil {
log.Fatal(err)
}
fmt.Print(string(bytes))
}
- Output:
Just the invoking line as remainder is, of course, as above.
$ go run self_print.go
Julia[edit]
The running program's filename is referenced as the builtin PROGRAM_FILE variable in Julia.
""" Read the program file and print it. """
printitself() = print(read(PROGRAM_FILE, String))
printitself()
Perl[edit]
# 20201011 added Perl programming solution
use strict;
use warnings;
open my $in, '<', $0 or die;
print while <$in>;
close($in)
# @ARGV=$0; print <> # slurp without an explicit open()
Phix[edit]
Interpreted only:
puts(1,get_text(command_line()[2]))
- Output:
puts(1,get_text(command_line()[2]))
Interpreted or compiled - latter only works while executable and source are still in the same directory, and not renamed.
puts(1,get_text(substitute(command_line()[2],".exe",".exw")))
- Output:
>p test ;; or p -c test puts(1,get_text(substitute(command_line()[2],".exe",".exw")))
Alternative - see the docs (ie phix.chm) for an explanation of the ("") and [1][2]:
?get_text(include_path("")&include_files()[1][2])
- Output:
"?get_text(include_path("")&include_files()[1][2])"
PowerShell[edit]
Write-Host $MyInvocation.MyCommand
Python[edit]
import sys
with open(sys.argv[0],'r') as input:
for row in input:
print(row, end='')
Raku[edit]
Not really sure what the point of this task is.
Is it supposed to be a quine?
my &f = {say $^s, $^s.raku;}; f "my \&f = \{say \$^s, \$^s.raku;}; f "
Or just a program that when executed echoes its source to STDOUT? (Here's probably the simplest valid program that when executed, echoes its source to STDOUT. It is exceptionally short: zero bytes; and when executed echoes zero bytes to STDOUT.)
Or are we supposed to demonstrate how to locate the currently executing source code file and incidentally, print it.
print $*PROGRAM.slurp
Whatever. Any of these satisfy the rather vague specifications.
REXX[edit]
/*REXX program prints its own multi─line source to the standard output (stdout). */
do j=1 for sourceline()
call lineout , sourceline(j)
end /*j*/ /*stick a fork in it, we're all done. */
Ring[edit]
fileName = filename()
fp = fopen(fileName,"r")
? read(filename())
fclose(fp)
- Output:
fileName = filename() fp = fopen(fileName,"r") ? read(filename()) fclose(fp)
Wren[edit]
import "os" for Process
import "io" for File
var args = Process.allArguments
System.write(File.read(args[1]))
- Output:
Just the invoking line as remainder is, of course, as above.
$ wren self_print.wren