Print itself: Difference between revisions

From Rosetta Code
Content added Content deleted
 
(33 intermediate revisions by 22 users not shown)
Line 7: Line 7:
:* [[Entropy/Narcissist]].
:* [[Entropy/Narcissist]].
<br>
<br>
{{omit from|Delphi}}
=={{header|11l}}==
<syntaxhighlight lang="11l">
:start:
-V sourceFileName = fs:path:split_ext(:argv[0])[0]‘.11l’
print(File(sourceFileName).read())
</syntaxhighlight>

=={{header|Ada}}==
<syntaxhighlight lang="ada">
-- Print the program's source to standard output
-- J. Carter 2023 Apr
-- Apparently it's acceptable to open the source file and copy it to the output

with Ada.Text_IO;

procedure Autoprint is
Source : Ada.Text_IO.File_Type;
begin -- Autoprint
Ada.Text_IO.Open (File => Source, Mode => Ada.Text_IO.In_File, Name => "autoprint.adb");
All_Lines : loop
exit All_Lines when Ada.Text_IO.End_Of_File (Source);
Ada.Text_IO.Put_Line (Item => Ada.Text_IO.Get_Line (Source) );
end loop All_Lines;
Ada.Text_IO.Close (File => Source);
end Autoprint;
</syntaxhighlight>

=={{header|ALGOL 68}}==
Using standard Algol 68 transput. Assumes the source is in a file called printItself.a68 in the current directory.
<syntaxhighlight lang="algol68">
IF FILE input file;
STRING file name = "printItself.a68";
open( input file, file name, stand in channel ) /= 0
THEN
# failed to open the file #
print( ( "Unable to open """ + file name + """", newline ) )
ELSE
# file opened OK #
BOOL at eof := FALSE;
on logical file end( input file # set the EOF handler for the file #
, ( REF FILE f )BOOL:
BEGIN
# note that we reached EOF on the latest read #
# and return TRUE so processing can continue #
at eof := TRUE
END
);
WHILE STRING line;
get( input file, ( line, newline ) );
NOT at eof
DO
print( ( line, newline ) )
OD;
close( input file )
FI
</syntaxhighlight>

{{Trans|FreeBASIC|Alternative version, using an OS command to print the source.}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Assumes the source is in a file called printItself2.a68 in the current directory.
<syntaxhighlight lang="algol68">
system( "type printItself2.a68" ) # replace type with cat for Linux #
</syntaxhighlight>

=={{header|Batch File}}==
<syntaxhighlight lang="dos">
@echo off
for /f "tokens=*" %%s in (%~n0%~x0) do (echo %%s)
</syntaxhighlight>

=={{header|Binary Lambda Calculus}}==
The 18 byte BLC program <code>16 46 80 05 bc bc fd f6 80 16 46 80 05 bc bc fd f6 80</code> prints itself.                                                     
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module test {
@Inject Console console;
void run() {
console.print($./test.x);
}
}
</syntaxhighlight>

{{out}}
<pre>
module test {
@Inject Console console;
void run() {
console.print($./test.x);
}
}
</pre>

=={{header|FreeBASIC}}==
This works for Linux.
<syntaxhighlight lang="freebasic">shell( "cat quine.bas" )</syntaxhighlight>


=={{header|Furor}}==
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
1 argv getfile dup sprint free
1 argv getfile dup sprint free
end
end
</syntaxhighlight>
</lang>

=={{header|Peri}}==
<syntaxhighlight lang="peri">
###sysinclude standard.uh
###sysinclude args.uh
###sysinclude str.uh
###sysinclude io.uh
1 argv getfile dup sprint
end
</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 32: Line 141:
}
}
fmt.Print(string(bytes))
fmt.Print(string(bytes))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 39: Line 148:
$ go run self_print.go
$ go run self_print.go
</pre>
</pre>

=={{header|J}}==

In J's command line environment, many programs, including the empty program (is nothing, takes no arguments, produces nothing), print themselves to standard output. This is especially true when the language has been configured (with <code>9!:3(5)</code>) to present verbs using their linear representation (which is highly recommendable as part of the system profile for most J users). But numeric constants can be thought of as programs which take no arguments and have themselves as their result.

For example:

<syntaxhighlight lang=J> 1
1
2 3 5
2 3 5
+/ % #
+/ % #</syntaxhighlight>

Though, of course, it's also true that these programs can be assembled as components in larger programs.

<syntaxhighlight lang=J> prim=: 2 3 5
mean=: +/ % #
mean prim
3.33333</syntaxhighlight>

=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''

A jq program that contains any JSON entity formatted as though by jq will print itself. The shortest such program would be a single digit, e.g.:
<syntaxhighlight lang="jq">0</syntaxhighlight>
{{out}}
Example invocation: jq -n 0
<pre>
0
</pre>

=={{header|Julia}}==
The running program's filename is referenced as the builtin PROGRAM_FILE variable in Julia.
<syntaxhighlight lang="julia">""" Read the program file and print it. """
printitself() = print(read(PROGRAM_FILE, String))

printitself()
</syntaxhighlight>

=={{header|Ksh}}==
<syntaxhighlight lang="ksh">#!/bin/ksh

# Program to print it's own source code

######
# main #
######
while read line; do
print "${line}"
done < $0</syntaxhighlight>

=={{header|Lua}}==

<syntaxhighlight lang="lua">-- arg[0] contains the name of the invoked script.
print(io.open(arg[0]):read"*a")</syntaxhighlight>

=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">println new(Nanoquery.IO.File).open(args[1]).readAll()</syntaxhighlight>

=={{header|Nim}}==
We suppose that the source file is in the same directory as the executable file.
<syntaxhighlight lang="nim">import os

let execFile = getAppFilename()
let sourceFile = execFile.addFileExt("nim")
stdout.write sourceFile.readFile()</syntaxhighlight>

=={{header|Perl}}==
<syntaxhighlight lang="perl"># 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()</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Interpreted only:
You can drop the substitute() if you plan to interpret rather than compile it.<br>
<syntaxhighlight lang="phix">puts(1,get_text(command_line()[2]))</syntaxhighlight>
It will not work, obviously, if you compile it (say test.exw) to test.exe and then either rename the executable or move it to some directory where there is no test.exw
{{out}}
<lang Phix>puts(1,get_text(substitute(command_line()[2],".exe",".exw")))</lang>
<pre>
puts(1,get_text(command_line()[2]))
</pre>
Interpreted or compiled - latter only works while executable and source are still in the same directory, and not renamed.
<syntaxhighlight lang="phix">puts(1,get_text(substitute(command_line()[2],".exe",".exw")))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 49: Line 243:
puts(1,get_text(substitute(command_line()[2],".exe",".exw")))
puts(1,get_text(substitute(command_line()[2],".exe",".exw")))
</pre>
</pre>
Alternative - see the docs (ie phix.chm) for an explanation of the ("") and [1][2]:
<syntaxhighlight lang="phix">?get_text(include_path("")&include_files()[1][2])</syntaxhighlight>
{{out}}
<pre>
"?get_text(include_path("")&include_files()[1][2])"
</pre>

=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
Write-Host $MyInvocation.MyCommand
</syntaxhighlight>

=={{header|Python}}==
<syntaxhighlight lang="python">
with open(__file__) as f:
print(f.read())
</syntaxhighlight>

=={{header|Quackery}}==

<syntaxhighlight lang="Quackery">[ this echo ]</syntaxhighlight>

{{out}}

<pre>[ this echo ]</pre>


=={{header|Raku}}==
=={{header|Raku}}==
Line 55: Line 274:


Is it supposed to be a quine?
Is it supposed to be a quine?
<lang perl6>my &f = {say $^s, $^s.raku;}; f "my \&f = \{say \$^s, \$^s.raku;}; f "
<syntaxhighlight lang="raku" line>my &f = {say $^s, $^s.raku;}; f "my \&f = \{say \$^s, \$^s.raku;}; f "
</syntaxhighlight>
</lang>


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


<syntaxhighlight lang="raku" line></syntaxhighlight>
<lang perl6></lang>


Or are we supposed to demonstrate how to locate the currently executing source code file and incidentally, print it.
Or are we supposed to demonstrate how to locate the currently executing source code file and incidentally, print it.


<lang perl6>print $*PROGRAM.slurp</lang>
<syntaxhighlight lang="raku" line>print $*PROGRAM.slurp</syntaxhighlight>


Whatever. Any of these satisfy the rather vague specifications.
Whatever. Any of these satisfy the rather vague specifications.


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program prints its own multi─line source to the standard output (stdout). */
<syntaxhighlight lang="rexx">/*REXX program prints its own multi─line source to the standard output (stdout). */


do j=1 for sourceline()
do j=1 for sourceline()
call lineout , sourceline(j)
call lineout , sourceline(j)
end /*j*/ /*stick a fork in it, we're all done. */</lang><br><br>
end /*j*/ /*stick a fork in it, we're all done. */</syntaxhighlight><br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
fileName = filename()
fileName = filename()
fp = fopen(fileName,"r")
fp = fopen(fileName,"r")
? read(filename())
? read(filename())
fclose(fp)
fclose(fp)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 89: Line 308:
fclose(fp)
fclose(fp)
</pre>
</pre>

=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
puts File.read(__FILE__)
</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "os" for Process
<syntaxhighlight lang="wren">import "os" for Process
import "io" for File
import "io" for File


var args = Process.allArguments
var args = Process.allArguments
System.write(File.read(args[1]))</lang>
System.write(File.read(args[1]))</syntaxhighlight>


{{out}}
{{out}}
Just the invoking line as remainder is, of course, as above.
Just the invoking line as remainder is, of course, as above.
<pre>
<pre>
$ wren self_print.wren
$ wren-cli Print_itself.wren
</pre>
</pre>

=={{header|Z80 Assembly}}==
This program prints its bytecode as text to the Amstrad CPC terminal. The program is run by typing <code>call &1000</code> to the screen.
<pre>WinAPE Z80 Assembler V1.0.13

000001 0000 (1001) org &1001
000003 1001 21 01 10 ld hl,&1001
000004 1004 1E FF ld e,&ff ;0 is the terminator so we can't use zero as an immediate directly
000005 1006 1C inc e ;we have to abuse 8-bit underflow to get it.
000006 1007 loop
000007 1007 7E ld a,(hl)
000008 1008 BB cp e
000009 1009 CA 2B 10 jp z,ProgramEnd
000011 100C CD 36 10 call UnpackNibbles
000012 100F 78 ld a,b
000013 1010 FE 0A cp &0A
000014 1012 38 02 jr c,noCorrectHex_B
000015 1014 C6 07 add &07
000016 1016 noCorrectHex_B
000017 1016 C6 30 add &30
000018 1018 CD 5A BB call &bb5a
000020 101B 79 ld a,c
000021 101C FE 0A cp &0A
000022 101E 38 02 jr c,noCorrectHex_C
000023 1020 C6 07 add &07
000024 1022 noCorrectHex_C
000025 1022 C6 30 add &30
000026 1024 CD 5A BB call &bb5a
000027 1027 23 inc hl
000028 1028 C3 07 10 jp loop
000029 102B ProgramEnd
000030 102B 3E 30 ld a,&30
000031 102D CD 5A BB call &bb5a
000032 1030 3E 30 ld a,&30
000033 1032 CD 5A BB call &bb5a
000034 1035 C9 ret ;return to basic
000037 1036 UnpackNibbles
000038 1036 ;splits a into its component nibbles, storing high nibble in B and low in C.
000039 1036 F5 push af
000040 1037 E6 0F and &0f
000041 1039 4F ld c,a
000042 103A F1 pop af
000043 103B E6 F0 and &f0
000044 103D 0F rrca
000045 103E 0F rrca
000046 103F 0F rrca
000047 1040 0F rrca
000048 1041 47 ld b,a
000049 1042 C9 ret
000051 1043 00 db 0 ;this must be the only instance of 00 in the bytecode for this to work.
</pre>
{{out}}
[https://ibb.co/KbzjpNQ Output on WinAPE]

Latest revision as of 16:23, 7 March 2024

Print itself is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Create a program, which prints its source code to the stdout!

Related tasks


11l

:start:
-V sourceFileName = fs:path:split_ext(:argv[0])[0]‘.11l’
print(File(sourceFileName).read())

Ada

-- Print the program's source to standard output
-- J. Carter     2023 Apr
-- Apparently it's acceptable to open the source file and copy it to the output

with Ada.Text_IO;

procedure Autoprint is
   Source : Ada.Text_IO.File_Type;
begin -- Autoprint
   Ada.Text_IO.Open (File => Source, Mode => Ada.Text_IO.In_File, Name => "autoprint.adb");
   
   All_Lines : loop
      exit All_Lines when Ada.Text_IO.End_Of_File (Source);
      
      Ada.Text_IO.Put_Line (Item => Ada.Text_IO.Get_Line (Source) );
   end loop All_Lines;
   
   Ada.Text_IO.Close (File => Source);
end Autoprint;

ALGOL 68

Using standard Algol 68 transput. Assumes the source is in a file called printItself.a68 in the current directory.

IF  FILE input file;
    STRING file name = "printItself.a68";
    open( input file, file name, stand in channel ) /= 0
THEN
    # failed to open the file                                              #
    print( ( "Unable to open """ + file name + """", newline ) )
ELSE
    # file opened OK                                                       #
    BOOL at eof := FALSE;
    on logical file end( input file     # set the EOF handler for the file #
                       , ( REF FILE f )BOOL:
                         BEGIN
                             # note that we reached EOF on the latest read #
                             # and return TRUE so processing can continue  #
                             at eof := TRUE
                         END
                       );
    WHILE STRING line;
          get( input file, ( line, newline ) );
          NOT at eof
    DO
        print( ( line, newline ) )
    OD;
    close( input file )
FI
Translation of: FreeBASIC – Alternative version, using an OS command to print the source.
Works with: ALGOL 68G version Any - tested with release 2.8.3.win32

Assumes the source is in a file called printItself2.a68 in the current directory.

system( "type printItself2.a68" ) # replace type with cat for Linux #

Batch File

@echo off
for /f "tokens=*" %%s in (%~n0%~x0) do (echo %%s)

Binary Lambda Calculus

The 18 byte BLC program 16 46 80 05 bc bc fd f6 80 16 46 80 05 bc bc fd f6 80 prints itself.                                                     

Ecstasy

module test {
    @Inject Console console;
    void run() {
        console.print($./test.x);
    }
}
Output:
module test {
    @Inject Console console;
    void run() {
        console.print($./test.x);
    }
}

FreeBASIC

This works for Linux.

shell( "cat quine.bas" )

Furor

1 argv getfile dup sprint free
end

Peri

###sysinclude standard.uh
###sysinclude args.uh
###sysinclude str.uh
###sysinclude io.uh
1 argv getfile dup sprint
end

Go

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

J

In J's command line environment, many programs, including the empty program (is nothing, takes no arguments, produces nothing), print themselves to standard output. This is especially true when the language has been configured (with 9!:3(5)) to present verbs using their linear representation (which is highly recommendable as part of the system profile for most J users). But numeric constants can be thought of as programs which take no arguments and have themselves as their result.

For example:

   1
1
   2 3 5
2 3 5
   +/ % #
+/ % #

Though, of course, it's also true that these programs can be assembled as components in larger programs.

   prim=: 2 3 5
   mean=: +/ % #
   mean prim
3.33333

jq

Works with: jq

Works with gojq, the Go implementation of jq

A jq program that contains any JSON entity formatted as though by jq will print itself. The shortest such program would be a single digit, e.g.:

0
Output:

Example invocation: jq -n 0

0

Julia

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

Ksh

#!/bin/ksh

# Program to print it's own source code

 ######
# main #
 ######
while read line; do
	print "${line}"
done < $0

Lua

-- arg[0] contains the name of the invoked script.
print(io.open(arg[0]):read"*a")

Nanoquery

println new(Nanoquery.IO.File).open(args[1]).readAll()

Nim

We suppose that the source file is in the same directory as the executable file.

import os

let execFile = getAppFilename()
let sourceFile = execFile.addFileExt("nim")
stdout.write sourceFile.readFile()

Perl

# 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

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

Write-Host $MyInvocation.MyCommand

Python

with open(__file__) as f:
    print(f.read())

Quackery

[ this echo ]
Output:
[ this echo ]

Raku

Works with: Rakudo version 2020.05

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

/*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

fileName = filename()
fp = fopen(fileName,"r")
? read(filename())
fclose(fp)
Output:
fileName = filename()
fp = fopen(fileName,"r")
? read(filename())
fclose(fp)

Ruby

puts File.read(__FILE__)

Wren

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-cli Print_itself.wren

Z80 Assembly

This program prints its bytecode as text to the Amstrad CPC terminal. The program is run by typing call &1000 to the screen.

WinAPE Z80 Assembler V1.0.13

000001  0000  (1001)        org &1001
000003  1001  21 01 10      ld hl,&1001
000004  1004  1E FF         ld e,&ff    ;0 is the terminator so we can't use zero as an immediate directly
000005  1006  1C            inc e       ;we have to abuse 8-bit underflow to get it.
000006  1007                loop
000007  1007  7E            ld a,(hl)
000008  1008  BB            cp e
000009  1009  CA 2B 10      jp z,ProgramEnd
000011  100C  CD 36 10      call UnpackNibbles
000012  100F  78            ld a,b
000013  1010  FE 0A         cp &0A
000014  1012  38 02         jr c,noCorrectHex_B
000015  1014  C6 07         add &07
000016  1016                noCorrectHex_B
000017  1016  C6 30         add &30
000018  1018  CD 5A BB      call &bb5a
000020  101B  79            ld a,c
000021  101C  FE 0A         cp &0A
000022  101E  38 02         jr c,noCorrectHex_C
000023  1020  C6 07         add &07
000024  1022                noCorrectHex_C
000025  1022  C6 30         add &30
000026  1024  CD 5A BB      call &bb5a
000027  1027  23            inc hl
000028  1028  C3 07 10      jp loop
000029  102B                ProgramEnd
000030  102B  3E 30         ld a,&30
000031  102D  CD 5A BB      call &bb5a
000032  1030  3E 30         ld a,&30
000033  1032  CD 5A BB      call &bb5a
000034  1035  C9            ret		;return to basic
000037  1036                UnpackNibbles
000038  1036                ;splits a into its component nibbles, storing high nibble in B and low in C.
000039  1036  F5            push af
000040  1037  E6 0F         and &0f
000041  1039  4F            ld c,a
000042  103A  F1            pop af
000043  103B  E6 F0         and &f0
000044  103D  0F            rrca
000045  103E  0F            rrca
000046  103F  0F            rrca
000047  1040  0F            rrca
000048  1041  47            ld b,a
000049  1042  C9            ret
000051  1043  00            db 0         ;this must be the only instance of 00 in the bytecode for this to work.
Output:

Output on WinAPE