Hello world/Line printer: Difference between revisions

From Rosetta Code
Content added Content deleted
(order messed up - sorry)
m (→‎{{header|Wren}}: Minor tidy)
 
(25 intermediate revisions by 18 users not shown)
Line 17: Line 17:
With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
<br><br>
<br><br>

=={{header|11l}}==
{{trans|Python}}

<syntaxhighlight lang="11l">V lp = File(‘/dev/lp0’, ‘w’)
lp.write("Hello World!\n")
lp.close()</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>HELLO CSECT
<syntaxhighlight lang="360asm">HELLO CSECT
PRINT NOGEN
PRINT NOGEN
BALR 12,0
BALR 12,0
Line 31: Line 38:
L1 DS 0CL133
L1 DS 0CL133
HW DC C'Hello World!'
HW DC C'Hello World!'
END HELLO</lang>
END HELLO</syntaxhighlight>

=={{header|Action!}}==
<syntaxhighlight lang="action!">Proc Main()
Open(1,"P:",8,0)
PrintDE(1,"HELLO WORLD!")
Close(1)
Return
</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
===[[Unix]]===
===[[Unix]]===
Assuming that the line printer is attached to /dev/lp0
Assuming that the line printer is attached to /dev/lp0
<syntaxhighlight lang="ada">
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;


Line 54: Line 69:
Close (Printer);
Close (Printer);
end Print_Line;
end Print_Line;
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 62: Line 77:
remote printer interfaced via CUPS. Extending it to other
remote printer interfaced via CUPS. Extending it to other
environments is left as an exercise for the reader.
environments is left as an exercise for the reader.
<lang algol68>
<syntaxhighlight lang="algol68">
BEGIN
BEGIN
STRING printer name = "/dev/lp0";
STRING printer name = "/dev/lp0";
Line 82: Line 97:
FI
FI
END
END
</lang> {{out}}
</syntaxhighlight> {{out}}
<pre>
<pre>
Can't contact line printer on /dev/lp0
Can't contact line printer on /dev/lp0
Line 92: Line 107:
Assumes a printer card is installed in the Apple II's number 1 expansion slot.
Assumes a printer card is installed in the Apple II's number 1 expansion slot.


<lang basic>
<syntaxhighlight lang="basic">
PR#1
PR#1
PRINT "HELLO WORLD!"
PRINT "HELLO WORLD!"
</syntaxhighlight>
</lang>

=={{header|Arturo}}==
<syntaxhighlight lang="arturo">write "/dev/lp0" "Hello World\n"</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
<lang AutoHotkey>
Fileappend, Hello World!, print.txt
Fileappend, Hello World!, print.txt
Run, print "print.txt"
Run, print "print.txt"
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
Unix / Linux:
Unix / Linux:
<syntaxhighlight lang="awk">
<lang AWK>
BEGIN { print("Hello World!") >"/dev/lp0" }
BEGIN { print("Hello World!") >"/dev/lp0" }
</syntaxhighlight>
</lang>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|GW-BASIC}}

{{works with|QBasic}}
{{works with|QBasic}}
{{works with|MSX BASIC}}

{{works with|ZX Spectrum Basic}}
{{works with|ZX Spectrum Basic}}

{{works with|Liberty BASIC}}
{{works with|Liberty BASIC}}
<syntaxhighlight lang="qbasic">LPRINT "Hello World!"</syntaxhighlight>

<lang qbasic>LPRINT "Hello World!"</lang>


==={{header|BaCon}}===
==={{header|BaCon}}===
Piping data to ''lp'' would also work. This example demonstrates writing to a device.
Piping data to ''lp'' would also work. This example demonstrates writing to a device.
<lang freebasic>' Hello, printer
<syntaxhighlight lang="freebasic">' Hello, printer
READ msg$
READ msg$
DATA "Hello World!\n"
DATA "Hello World!\n"
Line 128: Line 144:
OPEN "/dev/lp0" FOR DEVICE AS printer
OPEN "/dev/lp0" FOR DEVICE AS printer
PUTBYTE msg$ TO printer SIZE LEN(msg$)
PUTBYTE msg$ TO printer SIZE LEN(msg$)
CLOSE DEVICE printer</lang>
CLOSE DEVICE printer</syntaxhighlight>

==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">printeron
font "Arial", 20, 50
text 10,100, "Hello World!"
printeroff</syntaxhighlight>

==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> prn% = OPENOUT("PRN:")
PRINT #prn%, "Hello World!"
CLOSE #prn%</syntaxhighlight>

==={{header|GW-BASIC}}===
{{works with|BASICA}}
{{works with|PC-BASIC}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">LPRINT "Hello World!"</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>LPRINT "Hello World!"</lang>
<syntaxhighlight lang="is-basic">LPRINT "Hello World!"</syntaxhighlight>


=={{header|Batch File}}==
==={{header|MSX Basic}}===
<syntaxhighlight lang="qbasic">LPRINT "Hello World!"</syntaxhighlight>


==={{header|True BASIC}}===
<lang dos>ECHO Hello world!>PRN</lang>
<syntaxhighlight lang="qbasic">OPEN #1: PRINTER !Open channel #1 for the printer
PRINT #1: "Hello World!"
END</syntaxhighlight>


=={{header|BBC BASIC}}==
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">open window 100,100
{{works with|BBC BASIC for Windows}}
open printer
<lang bbcbasic> prn% = OPENOUT("PRN:")
PRINT #prn%, "Hello World!"
text 10, 50, "Hello World!"
close printer
CLOSE #prn%</lang>
close window</syntaxhighlight>

=={{header|Batch File}}==
<syntaxhighlight lang="dos">ECHO Hello world!>PRN</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
===[[Unix]]===
===[[Unix]]===
Assuming that the line printer is attached to /dev/lp0
Assuming that the line printer is attached to /dev/lp0
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


int main()
int main()
Line 155: Line 197:
fclose(lp);
fclose(lp);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
Line 162: Line 204:
which is out of scope of this example.
which is out of scope of this example.


<lang C sharp>
<syntaxhighlight lang="c sharp">
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
public class DOCINFOA
Line 222: Line 264:
ClosePrinter(hPrinter);
ClosePrinter(hPrinter);
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <fstream>
#include <fstream>


Line 234: Line 276:
lprFile.close();
lprFile.close();
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Clipper}}==
=={{header|Clipper}}==
<lang Clipper>SET PRINT ON
<syntaxhighlight lang="clipper">SET PRINT ON
SET CONSOLE OFF
SET CONSOLE OFF
? "Hello World!"
? "Hello World!"
SET PRINT OFF
SET PRINT OFF
SET CONSOLE ON
SET CONSOLE ON
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
Translated from Java (mechanically, as I don't understand how to test a line printer):
Translated from Java (mechanically, as I don't understand how to test a line printer):
<lang clojure>(ns rosetta-code.line-printer
<syntaxhighlight lang="clojure">(ns rosetta-code.line-printer
(:import java.io.FileWriter))
(:import java.io.FileWriter))


(defn -main [& args]
(defn -main [& args]
(with-open [wr (new FileWriter "/dev/lp0")]
(with-open [wr (new FileWriter "/dev/lp0")]
(.write wr "Hello, World!")))</lang>
(.write wr "Hello, World!")))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang COBOL>IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. GOODBYE-WORLD-PRINTER.
PROGRAM-ID. GOODBYE-WORLD-PRINTER.


Line 261: Line 303:
UPON PRINTER
UPON PRINTER
END-DISPLAY.
END-DISPLAY.
STOP RUN.</lang>
STOP RUN.</syntaxhighlight>


=={{header|Commodore BASIC}}==
=={{header|Commodore BASIC}}==
Most Commodore printer peripherals operate off the IEC bus commonly as device 4 or 5. It is also possible that some printers may be connected through the RS-232 serial port (typically device 2). This example assumes a device on the IEC bus with a default setting of device 4. This example does not utilize any printer control codes to change font, pitch, quality, graphics, etc., as those can vary between brands and models of printer.
Most Commodore printer peripherals operate off the IEC bus commonly as device 4 or 5. It is also possible that some printers may be connected through the RS-232 serial port (typically device 2). This example assumes a device on the IEC bus with a default setting of device 4. This example does not utilize any printer control codes to change font, pitch, quality, graphics, etc., as those can vary between brands and models of printer.


<syntaxhighlight lang="commodorebasicv2">
<lang CommodoreBASICv2>
10 rem rosetta code - "Hello World" on line printer
10 rem rosetta code - "Hello World" on line printer
20 open 7,4 : rem open <logical file number>, <device number>
20 open 7,4 : rem open <logical file number>, <device number>
30 print#7,"hello world!" : rem print line as shown to logical file number
30 print#7,"hello world!" : rem print line as shown to logical file number
40 close 7 : rem close the file number
40 close 7 : rem close the file number
</syntaxhighlight>
</lang>




=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Assuming that the line printer is attached to /dev/lp0
Assuming that the line printer is attached to /dev/lp0
<lang Lisp>(defun main ()
<syntaxhighlight lang="lisp">(defun main ()
(with-open-file (stream "/dev/lp0"
(with-open-file (stream "/dev/lp0"
:direction :output
:direction :output
Line 282: Line 324:
(format stream "Hello World~%")))
(format stream "Hello World~%")))
(main)
(main)
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main()
void main()
Line 292: Line 334:
lp.writeln("Hello World!");
lp.writeln("Hello World!");
}
}
</syntaxhighlight>
</lang>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program Project1;
<syntaxhighlight lang="delphi">program Project1;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 308: Line 350:
Writeln(lPrinterAsTextFile, 'Hello World!');
Writeln(lPrinterAsTextFile, 'Hello World!');
CloseFile(lPrinterAsTextFile);
CloseFile(lPrinterAsTextFile);
end.</lang>
end.</syntaxhighlight>

=={{header|Diego}}==
Once the caller has met the computer and its printer...
<syntaxhighlight lang="diego">with_computer(comp1)_printer(lp1)_text(Hello World!);</syntaxhighlight>
If the caller is the computer...
<syntaxhighlight lang="diego">with_printer(lp1)_text(Hello World!);</syntaxhighlight>


=={{header|Dragon}}==
=={{header|Dragon}}==
<lang dragon>
<syntaxhighlight lang="dragon">
select "files"
select "files"


Line 319: Line 367:
flush(f2)
flush(f2)
fclose(f2)
fclose(f2)
</syntaxhighlight>
</lang>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
EchoLisp supports a virtual printer which is not stdout. It is actually an extensible division of the HTML document, with printer pages as subdivisions. Printer and pages may be hidden/shown at convenience.
EchoLisp supports a virtual printer which is not stdout. It is actually an extensible division of the HTML document, with printer pages as subdivisions. Printer and pages may be hidden/shown at convenience.
<lang lisp>
<syntaxhighlight lang="lisp">
(printer-font "Courier") ;; change printer font
(printer-font "Courier") ;; change printer font
(printer-page "ROSETTA CODE") ;; starts a new page with nice header
(printer-page "ROSETTA CODE") ;; starts a new page with nice header
(printer-writeln "Hello World!") ;; prints new line (not seen on stdout)
(printer-writeln "Hello World!") ;; prints new line (not seen on stdout)
</syntaxhighlight>
</lang>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
This program uses self-modifying code to loop through an array of characters. Since the EDSAC character set does not include lower-case letters or exclamation marks, we actually print <tt>HELLO WORLD</tt> followed by a carriage return and a line feed. Strings cannot be null-terminated, because 0 happens to be the character code for <tt>P</tt>; instead, we mark the final character by including a 1 (which has no printable effect) in the least significant bit.
This program uses self-modifying code to loop through an array of characters. Since the EDSAC character set does not include lower-case letters or exclamation marks, we actually print <tt>HELLO WORLD</tt> followed by a carriage return and a line feed. Strings cannot be null-terminated, because 0 happens to be the character code for <tt>P</tt>; instead, we mark the final character by including a 1 (which has no printable effect) in the least significant bit.
<lang edsac>[ Hello world
<syntaxhighlight lang="edsac">[ Hello world
===========
===========


Line 391: Line 439:
&D [ Line feed + 1 ]
&D [ Line feed + 1 ]


EZPF</lang>
EZPF</syntaxhighlight>

=== Alternative ===
As noted, null in the sense of zero cannot be used as a string terminator on EDSAC. However, it is possible to use the EDSAC null, whose 5-bit code is 10000. The subroutine below demonstrates this.

After the string characters, the terminating null is also sent to the teleprinter. This is because the teleprinter had a one-character buffer, so that an O order did not print its own character immediately, but stored it in the buffer and printed the character set up by the previous O order (Wilkes, Wheeler & Gill, 1951 edition, page 50). Sending the terminating null to the teleprinter ensures that the last character of the string is printed at the same time as the rest.

The EDSAC PC simulator allows .F for null and *F for letter shift, but it seems from WWG that on the original EDSAC these had to be input as K4096F and K2048F respectively.
<syntaxhighlight lang="edsac">
[Alternative "Hello World" for Rosetta Code]

[Subroutine to print a string.]
[Parameter: A order for first character follows subroutine call (G order).]
[Modified 2022-07-13: A order for first character was formerly passed in 0F.]
[String is terminated with EDSAC null, which is printed]
T56K GK [load at 56; set relative addressing]
A18@ U17@ [plant return link, increasing address by 3
instead of 2 as usual]
S19@ [make A order to load A order after subroutine call]
T4@ [plant in code]
[4] AF [(planted) load A order after subroutine call]
[5] T6@ [loop: plant A order for next character]
[6] AF [load next character]
UF [to 0F for printing; keep it in acc]
OF [output to teleprinter]
E12@ [if char >= 0, not EDSAC null]
A20@ [if char < 0, add 15 to test for EDSAC null]
G16@ [jump to exit if null]
[12] TF [clear acc]
A6@ A2F [inc address in A order above]
G5@ [loop back, because top 5 bits = A = 11100]
[16] TF [clear acc on exit (EDSAC convention)]
[17] ZF [(planted) jump back to caller]
[18] U3F [constant for making return link]
[19] U1F [constant for picking up parameter]
[20] K2048F [constant for testing final null]

[Main routine]
T96K GK [load at 96; set relative addressing
[Enter with acc = 0]
[0] A@ G56F [call print subroutine]
A4@ [A order for first character of string]
ZF [subroutine returns here; halt machine]
[4] K2048F HF EF LF LF OF !F WF OF RF LF DF @F &F K4096F
[The above string is: letter shift, 'HELLO WORLD', CR, LF, null]
EZ [define entry point]
PF [acc = 0 on entry]
[end]
</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
! Hello World in ERRE language
! Hello World in ERRE language
PROGRAM HELLO
PROGRAM HELLO
Line 402: Line 498:
!$NOREDIR
!$NOREDIR
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>


Prints on LPT1: (if exists) without opening a file.
Prints on LPT1: (if exists) without opening a file.
Line 411: Line 507:
Prints through Unix "lpr" command.
Prints through Unix "lpr" command.


<lang factor>( scratchpad ) USE: io.encodings.utf8
<syntaxhighlight lang="factor">( scratchpad ) USE: io.encodings.utf8
( scratchpad ) USE: io.launcher
( scratchpad ) USE: io.launcher
( scratchpad ) "lpr" utf8 [ "Hello World!" print ] with-process-writer</lang>
( scratchpad ) "lpr" utf8 [ "Hello World!" print ] with-process-writer</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
Forth systems currently run on everything from bare metal to modern multi-user operating systems and printers are handled differently on each. This demonstration shows a common way that text output is re-directed to printers and/or other devices by vectoring the action of the Forth word EMIT. Emit takes one character off the stack and outputs it to a device. By defining all I/O with the primitive operation EMIT, we can vector the output anywhere we choose, even on hardware with no O/S. Here we show a very basic printer device driver for an embedded system that adds I/O re-direction to the system's Forth language.
Forth systems currently run on everything from bare metal to modern multi-user operating systems and printers are handled differently on each. This demonstration shows a common way that text output is re-directed to printers and/or other devices by vectoring the action of the Forth word EMIT. Emit takes one character off the stack and outputs it to a device. By defining all I/O with the primitive operation EMIT, we can vector the output anywhere we choose, even on hardware with no O/S. Here we show a very basic printer device driver for an embedded system that adds I/O re-direction to the system's Forth language.
<lang Forth>\ No operating system, embedded device, printer output example
<syntaxhighlight lang="forth">\ No operating system, embedded device, printer output example


defer emit \ deferred words in Forth are a place holder for an
defer emit \ deferred words in Forth are a place holder for an
Line 442: Line 538:
\ vector control words
\ vector control words
: >console ['] console-emit is EMIT ; \ assign the execution token of console-emit to EMIT
: >console ['] console-emit is EMIT ; \ assign the execution token of console-emit to EMIT
: >printer ['] printer-emit is EMIT ; \ assign the execution token of printer-emit to EMIT</lang>
: >printer ['] printer-emit is EMIT ; \ assign the execution token of printer-emit to EMIT</syntaxhighlight>


Usage Examples:
Usage Examples:
Line 466: Line 562:


Since for a new job, output would commence with the lineprinter already at the top of a new page, an overprint (no carriage advance) thus means writing to the very first line. If however, top-of-page placement was not assured at your installation, then "1HELLO WORLD!" would do.
Since for a new job, output would commence with the lineprinter already at the top of a new page, an overprint (no carriage advance) thus means writing to the very first line. If however, top-of-page placement was not assured at your installation, then "1HELLO WORLD!" would do.
<lang Fortran> WRITE (6,1)
<syntaxhighlight lang="fortran"> WRITE (6,1)
1 FORMAT ("+HELLO WORLD!")
1 FORMAT ("+HELLO WORLD!")
END </lang>
END </syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Open Lpt "Lpt:" As #1 '' prints to default printer
Open Lpt "Lpt:" As #1 '' prints to default printer
Print #1, "Hello World!"
Print #1, "Hello World!"
Close #1</lang>
Close #1</syntaxhighlight>

=={{header|FutureBasic}}==
The legacy lprint statemenet sends a line of text to the printer. The @(col,row) and %(h,v) options specify where on the page the line should be printed (see the print statement); if you don't specify one of these, the line is printed at the current pen position, usually just under the previously-printed line. lprint is inefficient if you are printing many lines to a page because it reroutes the output each time lprint is executed. In such cases, it's better to execute a sequence of print statements, with the entire sequence preceded by a single route _toPrinter statement and followed by a single route _toScreen statement. FB progammers today use much more sophisticated printer functions designed for complex pagination.
<syntaxhighlight lang="futurebasic">
// lprint [@(col,row)|%(h,v)] "Hello,World!"
lprint "Hello,World!"
route _toScreen
close lprint
</syntaxhighlight>


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


import (
import (
Line 495: Line 600:


fmt.Fprintln(lp0, "Hello World!")
fmt.Fprintln(lp0, "Hello World!")
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>new File('/dev/lp0').write('Hello World!\n')
<syntaxhighlight lang="groovy">new File('/dev/lp0').write('Hello World!\n')
</syntaxhighlight>
</lang>


=={{header|GUISS}}==
=={{header|GUISS}}==


<lang guiss>Start,Programs,Accessories,Notepad,Type:Goodbye World[pling],
<syntaxhighlight lang="guiss">Start,Programs,Accessories,Notepad,Type:Goodbye World[pling],
Menu:File,Print,Button:OK</lang>
Menu:File,Print,Button:OK</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
<lang visualfoxpro>SET PRINT ON
<syntaxhighlight lang="visualfoxpro">SET PRINT ON
SET CONSOLE OFF
SET CONSOLE OFF
? "Hello World!"
? "Hello World!"
SET PRINT OFF
SET PRINT OFF
SET CONSOLE ON</lang>
SET CONSOLE ON</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.Process (ProcessHandle, runCommand)
<syntaxhighlight lang="haskell">import System.Process (ProcessHandle, runCommand)


main :: IO ProcessHandle
main :: IO ProcessHandle
main = runCommand "echo \"Hello World!\" | lpr"</lang>
main = runCommand "echo \"Hello World!\" | lpr"</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 523: Line 628:
Works in both languages, provided printer is attached to <tt>/dev/lp0</tt>.
Works in both languages, provided printer is attached to <tt>/dev/lp0</tt>.


<lang unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()
write(open("/dev/lp0","w"),"Hello, world!")
write(open("/dev/lp0","w"),"Hello, world!")
end</lang>
end</syntaxhighlight>


=={{header|Integer BASIC}}==
=={{header|Integer BASIC}}==
Line 533: Line 638:
=={{header|J}}==
=={{header|J}}==


<lang j>require'print'
<syntaxhighlight lang="j">require'print'
print'Hello world!'</lang>
print'Hello world!'</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==


<lang java>import java.io.FileWriter;
<syntaxhighlight lang="java">import java.io.FileWriter;
import java.io.IOException;
import java.io.IOException;
Line 551: Line 656:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
{{works with|Node.js}}
{{works with|Node.js}}
<lang javascript>// This example runs on Node.js
<syntaxhighlight lang="javascript">// This example runs on Node.js
var fs = require('fs');
var fs = require('fs');
// Assuming lp is at /dev/lp0
// Assuming lp is at /dev/lp0
var lp = fs.openSync('/dev/lp0', 'w');
var lp = fs.openSync('/dev/lp0', 'w');
fs.writeSync(lp, 'Hello, world!\n');
fs.writeSync(lp, 'Hello, world!\n');
fs.close(lp);</lang>
fs.close(lp);</syntaxhighlight>
{{works with|Firefox}}
{{works with|Firefox}}
{{works with|Chromium}}
{{works with|Chromium}}
<lang javascript>
<syntaxhighlight lang="javascript">
document.write("Hello World!");
document.write("Hello World!");
print(); //Opens a dialog.
print(); //Opens a dialog.
</syntaxhighlight>
</lang>

=={{header|Joy}}==
<syntaxhighlight lang="joy">"/dev/lp" "w" fopen "Hello World!\n" fputchars fclose.</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>
<syntaxhighlight lang="julia">
lineprinter = Sys.iswindows() ? "LPT3" : "/dev/lp0"
lineprinter = Sys.iswindows() ? "LPT3" : "/dev/lp0"
lp = open(lineprinter, "w")
lp = open(lineprinter, "w")
write(lp, "Hello world")
write(lp, "Hello world")
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{Works with|Ubuntu|14.04}}
{{Works with|Ubuntu|14.04}}
<lang scala>import java.io.File
<syntaxhighlight lang="scala">import java.io.File


fun main(args: Array<String>) {
fun main(args: Array<String>) {
val text = "Hello World!\n"
val text = "Hello World!\n"
File("/dev/lp0").writeText(text)
File("/dev/lp0").writeText(text)
}</lang>
}</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==


<lang lasso>File_Write: '/dev/lp0', 'Hello world', -FileOverWrite;</lang>
<syntaxhighlight lang="lasso">File_Write: '/dev/lp0', 'Hello world', -FileOverWrite;</syntaxhighlight>


=={{header|Locomotive Basic}}==
=={{header|Locomotive Basic}}==


<lang locobasic>10 PRINT #8, "Hello World!"</lang>
<syntaxhighlight lang="locobasic">10 PRINT #8, "Hello World!"</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
We can use printer like a page printer
We can use printer like a page printer
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Printer {
Printer {
\\ just change the current layer to Print Page
\\ just change the current layer to Print Page
Line 600: Line 708:
Print "Hello World!"
Print "Hello World!"
}
}
</syntaxhighlight>
</lang>


Or we can use ANSI output using a file for export in Lpt1
Or we can use ANSI output using a file for export in Lpt1


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Try ok {
Try ok {
Open "Lpt1" For OutPut As N '' prints to Lpt1 if exist a printer
Open "Lpt1" For OutPut As N '' prints to Lpt1 if exist a printer
Line 611: Line 719:
}
}
If Not Ok Then Print "Can't Print"
If Not Ok Then Print "Can't Print"
</syntaxhighlight>
</lang>


If we have a file in current dir we can use a Dos command:
If we have a file in current dir we can use a Dos command:
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Dos "Print /d:lpt1 file " +quote$(dir$+"this.txt");
Dos "Print /d:lpt1 file " +quote$(dir$+"this.txt");
</syntaxhighlight>
</lang>
Using ; at the end of DOS command we have no open terminal
Using ; at the end of DOS command we have no open terminal


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Dos "command" [, sleep time after call] [;]
Dos "command" [, sleep time after call] [;]
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>lprint("Hello World!")</lang>
<syntaxhighlight lang="maple">lprint("Hello World!")</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>commandstring = "echo Hello World! | lpr -P Printer01"
<syntaxhighlight lang="mathematica">commandstring = "echo Hello World! | lpr -P Printer01"
Run[commandstring]</lang>
Run[commandstring]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
===[[Unix]]===
===[[Unix]]===
Assuming that the line printer is attached to /dev/lp0
Assuming that the line printer is attached to /dev/lp0
<lang Matlab> fid = fopen('/dev/lp0');
<syntaxhighlight lang="matlab"> fid = fopen('/dev/lp0');
fprintf(fid,'Hello World!\n');
fprintf(fid,'Hello World!\n');
fclose(fid);</lang>
fclose(fid);</syntaxhighlight>


=={{header|MIXAL}}==
=={{header|MIXAL}}==
<syntaxhighlight lang="mixal">
<lang MIXAL>
LPR EQU 18
LPR EQU 18
STRING EQU 2000
STRING EQU 2000
Line 650: Line 758:
ALF D!
ALF D!
END START
END START
</syntaxhighlight>
</lang>


=={{header|N/t/roff}}==
=={{header|N/t/roff}}==
Line 665: Line 773:
Because /.ROFF/ is a document formatting language, the majority of lines in a typical /.ROFF/ source file is to be textual input. This input is typeset directly onto the output medium. Therefore, the user need not call a procedure to print text to any terminal.
Because /.ROFF/ is a document formatting language, the majority of lines in a typical /.ROFF/ source file is to be textual input. This input is typeset directly onto the output medium. Therefore, the user need not call a procedure to print text to any terminal.


<lang N/t/roff>
<syntaxhighlight lang="n/t/roff">
Hello World!
Hello World!
</syntaxhighlight>
</lang>


=={{header|Nim}}==
=={{header|Nim}}==
Assuming that the line printer is attached to /dev/lp0:
Assuming that the line printer is attached to /dev/lp0:
<lang nim>var lp = open("/dev/lp0", fmWrite)
<syntaxhighlight lang="nim">var lp = open("/dev/lp0", fmWrite)
lp.writeln "Hello World"
lp.writeLine "Hello World"
lp.close()</lang>
lp.close()</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Assuming that the line printer is attached to /dev/lp0
Assuming that the line printer is attached to /dev/lp0
<lang ocaml>let () =
<syntaxhighlight lang="ocaml">let () =
let oc = open_out "/dev/lp0" in
let oc = open_out "/dev/lp0" in
output_string oc "Hello world!\n";
output_string oc "Hello world!\n";
close_out oc ;;</lang>
close_out oc ;;</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang Oforth>File new("/dev/lp0") dup open(File.WRITE) "Hello world\n" << close</lang>
<syntaxhighlight lang="oforth">File new("/dev/lp0") dup open(File.WRITE) "Hello world\n" << close</syntaxhighlight>

=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(define p (open-output-file "/dev/lp0"))
(when p
(print-to p "Hello world!")
(close-port p))
</syntaxhighlight>


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang progress>OUTPUT TO PRINTER.
<syntaxhighlight lang="progress">OUTPUT TO PRINTER.
PUT UNFORMATTED "Hello world!" SKIP.
PUT UNFORMATTED "Hello world!" SKIP.
OUTPUT CLOSE.</lang>
OUTPUT CLOSE.</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 694: Line 810:
{{libheader|Printer}}
{{libheader|Printer}}
Example from the FreePascal documentation:
Example from the FreePascal documentation:
<lang pascal>program testprn;
<syntaxhighlight lang="pascal">program testprn;
uses printer;
uses printer;
var i: integer;
var i: integer;
Line 714: Line 830:
writeln ( 'Done.' )
writeln ( 'Done.' )
{$endif}
{$endif}
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Assuming that the line printer is attached to /dev/lp0
Assuming that the line printer is attached to /dev/lp0
<lang perl>open O, ">", "/dev/lp0";
<syntaxhighlight lang="perl">open O, ">", "/dev/lp0";
print O "Hello World!\n";
print O "Hello World!\n";
close O;</lang>
close O;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
If you have not got something appropriate attached, this will just hang. Other values you can try, on windows: "AUX", "COM1", "COM2", "LPT1"
If you have not got something appropriate attached, this will just hang. Other values you can try, on windows: "AUX", "COM1", "COM2", "LPT1"
<!--<syntaxhighlight lang="phix">-->
<lang Phix>integer fn = open(iff(platform()=WIN32?"PRN":"/dev/lp0"),"w")
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #000000;">WIN32</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"PRN"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"/dev/lp0"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"w"</span><span style="color: #0000FF;">)</span>
if fn=-1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
puts(1,"some error")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"some error"</span><span style="color: #0000FF;">)</span>
else
<span style="color: #008080;">else</span>
puts(fn,"Hello World!")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Hello World!"</span><span style="color: #0000FF;">)</span>
close(fn)
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
puts(1,"success!")
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"success!"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
{} = wait_key()</lang>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">wait_key</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
<lang PHP><?php
<syntaxhighlight lang="php"><?php
file_put_contents('/dev/lp0', 'Hello world!');
file_put_contents('/dev/lp0', 'Hello world!');
?></lang>
?></syntaxhighlight>


<lang PHP><?php
<syntaxhighlight lang="php"><?php
fclose(STDOUT);
fclose(STDOUT);
$STDOUT = fopen('/dev/lp0', 'a');
$STDOUT = fopen('/dev/lp0', 'a');
echo 'Hello world!';
echo 'Hello world!';
?></lang>
?></syntaxhighlight>

=={{header|Picat}}==
{{works with|Picat}}
<syntaxhighlight lang="picat">
main =>
Printer = open("/dev/lp0", write),
println(Printer, "Hello, world!"),
flush(Printer),
close(Printer).
</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(out '(lpr "-P" "Printer01")
<syntaxhighlight lang="picolisp">(out '(lpr "-P" "Printer01")
(prinl "Hello world") )</lang>
(prinl "Hello world") )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>
<syntaxhighlight lang="pli">
hello: procedure options(main);
hello: procedure options(main);
put skip list('Hello world.');
put skip list('Hello world.');
end hello;</lang>
end hello;</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
Technically not really correct, as this has to be sent to the printer directly.
Technically not really correct, as this has to be sent to the printer directly.
It will output Hello world, then, though.
It will output Hello world, then, though.
<lang postscript><</PageSize [595 842]>> setpagedevice % set page size to DIN A4
<syntaxhighlight lang="postscript"><</PageSize [595 842]>> setpagedevice % set page size to DIN A4
/Courier findfont % use Courier
/Courier findfont % use Courier
12 scalefont setfont % 12 pt
12 scalefont setfont % 12 pt
28 802 moveto % 1 cm from the top and left edges
28 802 moveto % 1 cm from the top and left edges
(Hello world) show % draw the string</lang>
(Hello world) show % draw the string</syntaxhighlight>

=={{header|Prolog}}==
{{works with|SWI Prolog}}
<syntaxhighlight lang="prolog">
:- initialization(main).

main :-
open("/dev/lp0", write, Printer),
writeln(Printer, "Hello, world!"),
flush_output(Printer),
close(Printer).
</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
{{libheader|PureLPRINT}}
{{libheader|PureLPRINT}}
<lang PureBasic>MyPrinter$ = LPRINT_GetDefaultPrinter()
<syntaxhighlight lang="purebasic">MyPrinter$ = LPRINT_GetDefaultPrinter()
If LPRINT_OpenPrinter(MyPrinter$)
If LPRINT_OpenPrinter(MyPrinter$)
If LPRINT_StartDoc("Printing a RC-Task")
If LPRINT_StartDoc("Printing a RC-Task")
Line 775: Line 915:
EndIf
EndIf
LPRINT_ClosePrinter()
LPRINT_ClosePrinter()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Assuming that the line printer is attached to /dev/lp0:
Assuming that the line printer is attached to /dev/lp0:
<lang python>lp = open("/dev/lp0")
<syntaxhighlight lang="python">lp = open("/dev/lp0")
lp.write("Hello World!\n")
lp.write("Hello World!\n")
lp.close()</lang>
lp.close()</syntaxhighlight>


If the above code gives you the error "IOError: File not open for writing", try:
If the above code gives you the error "IOError: File not open for writing", try:
<lang python>lp = open("/dev/lp0","w")
<syntaxhighlight lang="python">lp = open("/dev/lp0","w")
lp.write("Hello World!\n")
lp.write("Hello World!\n")
lp.close()</lang>
lp.close()</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define (print text)
(define (print text)
Line 802: Line 942:
(λ() (displayln text)))))
(λ() (displayln text)))))
(print "Hello World!")
(print "Hello World!")
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>my $lp = open '/dev/lp0', :w;
<syntaxhighlight lang="raku" line>my $lp = open '/dev/lp0', :w;
$lp.say: 'Hello World!';
$lp.say: 'Hello World!';
$lp.close;</lang>
$lp.close;</syntaxhighlight>


Or using <code>given</code> to avoid having to write the variable name repeatedly:
Or using <code>given</code> to avoid having to write the variable name repeatedly:


<lang perl6>given open '/dev/lp0', :w {
<syntaxhighlight lang="raku" line>given open '/dev/lp0', :w {
.say: 'Hello World!';
.say: 'Hello World!';
.close;
.close;
}</lang>
}</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 822: Line 962:
but a shell command could be used.
but a shell command could be used.
<br><br>In DOS (or under Windows):
<br><br>In DOS (or under Windows):
<lang rexx>/*REXX program prints a string to the (DOS) line printer via redirection to a printer.*/
<syntaxhighlight lang="rexx">/*REXX program prints a string to the (DOS) line printer via redirection to a printer.*/
$= 'Hello World!' /*define a string to be used for output*/
$= 'Hello World!' /*define a string to be used for output*/
'@ECHO' $ ">PRN" /*stick a fork in it, we're all done. */</lang>
'@ECHO' $ ">PRN" /*stick a fork in it, we're all done. */</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
lp = fopen("/dev/lp0","w") fputs(lp,"Hello world!") fclose(lp)
lp = fopen("/dev/lp0","w") fputs(lp,"Hello world!") fclose(lp)
</syntaxhighlight>
</lang>


=={{header|RPG}}==
=={{header|RPG}}==
{{works with|ILE RPG}}
{{works with|ILE RPG}}
<syntaxhighlight lang="rpg">
<lang RPG>
Fqsysprt O F 80 printer
Fqsysprt O F 80 printer
C except
C except
Line 839: Line 979:
Oqsysprt E
Oqsysprt E
O 11 'Hello world'
O 11 'Hello world'
</syntaxhighlight>
</lang>

=={{header|RPL}}==
"Hello world!" PR1


=={{header|Ruby}}==
=={{header|Ruby}}==
Assumes that <code>lpr</code> command reaches printer.
Assumes that <code>lpr</code> command reaches printer.


<lang ruby>open("| lpr", "w") { |f| f.puts "Hello World!" }</lang>
<syntaxhighlight lang="ruby">open("| lpr", "w") { |f| f.puts "Hello World!" }</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic> shell$("echo \"Hello World!\" | lpr")</lang>
<syntaxhighlight lang="runbasic"> shell$("echo \"Hello World!\" | lpr")</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
===Unix===
===Unix===
<lang rust>use std::fs::OpenOptions;
<syntaxhighlight lang="rust">use std::fs::OpenOptions;
use std::io::Write;
use std::io::Write;


Line 857: Line 1,000:
let file = OpenOptions::new().write(true).open("/dev/lp0").unwrap();
let file = OpenOptions::new().write(true).open("/dev/lp0").unwrap();
file.write(b"Hello, World!").unwrap();
file.write(b"Hello, World!").unwrap();
}</lang>
}</syntaxhighlight>


=={{header|Salmon}}==
=={{header|Salmon}}==
Assuming /dev/lp0 accesses the printer:
Assuming /dev/lp0 accesses the printer:


<lang Salmon>open_output_text_file("/dev/lp0").print("Hello World!");</lang>
<syntaxhighlight lang="salmon">open_output_text_file("/dev/lp0").print("Hello World!");</syntaxhighlight>


Assuming lpr is a command that prints to a printer:
Assuming lpr is a command that prints to a printer:
<lang Salmon>`echo "Hello World!" | lpr`;</lang>
<syntaxhighlight lang="salmon">`echo "Hello World!" | lpr`;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}
{{libheader|Scala}}
===All platforms===
===All platforms===
<lang scala>import java.awt.print.PrinterException
<syntaxhighlight lang="scala">import java.awt.print.PrinterException
import scala.swing.TextArea
import scala.swing.TextArea


Line 884: Line 1,027:
}
}
println("Document printed.")
println("Document printed.")
}</lang>
}</syntaxhighlight>


===[[Unix]]===
===[[Unix]]===
Assuming device is attached to lp0
Assuming device is attached to lp0
<lang Scala>object LinePrinter extends App {
<syntaxhighlight lang="scala">object LinePrinter extends App {
import java.io.{ FileWriter, IOException }
import java.io.{ FileWriter, IOException }
{
{
Line 895: Line 1,038:
lp0.close()
lp0.close()
}
}
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
===[[Unix]]===
===[[Unix]]===
Assuming device is attached to lp0
Assuming device is attached to lp0
<lang scheme>(call-with-output-file "/dev/lp0"
<syntaxhighlight lang="scheme">(call-with-output-file "/dev/lp0"
  (lambda (printer)
  (lambda (printer)
    (write "Hello World!" printer)))</lang>
    (write "Hello World!" printer)))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Assuming that the line printer is attached to /dev/lp0:
Assuming that the line printer is attached to /dev/lp0:
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
const proc: main is func
Line 915: Line 1,058:
writeln(lp, "Hello world!");
writeln(lp, "Hello world!");
close(lp);
close(lp);
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>Sys.open(\var fh, '>', '/dev/lp0') \
<syntaxhighlight lang="ruby">Sys.open(\var fh, '>', '/dev/lp0') \
&& fh.say("Hello World!") \
&& fh.say("Hello World!") \
&& fh.close</lang>
&& fh.close</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
{{works with|SIMULA-67}}
{{works with|SIMULA-67}}
<lang simula>BEGIN
<syntaxhighlight lang="simula">BEGIN
OUTTEXT("Hello World!");
OUTTEXT("Hello World!");
OUTIMAGE
OUTIMAGE
END</lang>
END</syntaxhighlight>

=={{header|Slope}}==
<syntaxhighlight>(file-append-to "/dev/lp0" "Hello world!")</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
portable (dispatches to one of bellow):
<syntaxhighlight lang="smalltalk">s := PrinterStream defaultPrinter new.
s nextPutLine:'Hello, world'.
s close</syntaxhighlight>
===[[Unix]]===
===[[Unix]]===
<syntaxhighlight lang="smalltalk">s := PipeStream writingTo:'lpr'.
<lang smalltalk></lang>
s nextPutLine:'Hello, world'.
s close.</syntaxhighlight>
alternative:
<syntaxhighlight lang="smalltalk">'/dev/lp0' asFilename writingFileDo:[:s |
s nextPutLine:'Hello, world'.
]</syntaxhighlight>
===[[Windows]]===
<syntaxhighlight lang="smalltalk">s := WinPrinterStream new.
s nextPutLine:'Hello, world'.
s close.</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 940: Line 1,100:
By default, the variable "input" is associated with standard input, and the variable "output" is associated with standard output.
By default, the variable "input" is associated with standard input, and the variable "output" is associated with standard output.


<lang SNOBOL4> output = "Hello, world."</lang>
<syntaxhighlight lang="snobol4"> output = "Hello, world."</syntaxhighlight>


You can associate the variable "print" with lpt1 (the default local printer port) using the output() function:
You can associate the variable "print" with lpt1 (the default local printer port) using the output() function:


<lang SNOBOL4> output(.print,25,"lpt1")
<syntaxhighlight lang="snobol4"> output(.print,25,"lpt1")
print = "Hello, world."</lang>
print = "Hello, world."</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


let out = NSOutputStream(toFileAtPath: "/dev/lp0", append: true)
let out = NSOutputStream(toFileAtPath: "/dev/lp0", append: true)
Line 954: Line 1,114:
out?.open()
out?.open()
out?.write(UnsafePointer<UInt8>(data!.bytes), maxLength: data!.length)
out?.write(UnsafePointer<UInt8>(data!.bytes), maxLength: data!.length)
out?.close()</lang>
out?.close()</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==


===[[Unix]]===
===[[Unix]]===
<lang tcl>exec lp << "Hello World!"</lang>
<syntaxhighlight lang="tcl">exec lp << "Hello World!"</syntaxhighlight>
<lang tcl>set f [open |lp w]
<syntaxhighlight lang="tcl">set f [open |lp w]
puts $f "Hello World!"
puts $f "Hello World!"
close $f</lang>
close $f</syntaxhighlight>


===[[Windows]]===
===[[Windows]]===


<lang tcl>set f [open prn w]
<syntaxhighlight lang="tcl">set f [open prn w]
puts $f "Hello World!"
puts $f "Hello World!"
close $f</lang>
close $f</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
Use ''one'' of the following lines.
Use ''one'' of the following lines.


<lang bash># Use the default printer queue, with lp(1) or lpr(1).
<syntaxhighlight lang="bash"># Use the default printer queue, with lp(1) or lpr(1).
# 1. The system must have a printer queue.
# 1. The system must have a printer queue.
# 2. The printer queue must understand plain text.
# 2. The printer queue must understand plain text.
Line 993: Line 1,153:
echo 'Hello World!' >/dev/lp0
echo 'Hello World!' >/dev/lp0
echo 'Hello World!' >/dev/lpt0
echo 'Hello World!' >/dev/lpt0
echo 'Hello World!' >/dev/ulpt0</lang>
echo 'Hello World!' >/dev/ulpt0</syntaxhighlight>

=={{header|Wisp}}==
===[[Unix]]===
Assuming that the device is attached to lp0
<syntaxhighlight lang="wisp">call-with-output-file "/dev/lp0"
λ : printer
write "Hello World!" printer</syntaxhighlight>

=={{header|Wren}}==
It is not currently possible to communicate with the printer using Wren-cli. So we need to write a minimal embedded program (no error checking) so the C host can do this for us.
<syntaxhighlight lang="wren">/* Hello_world_Line_printer.wren */

class C {
foreign static lprint(s)
}

C.lprint("Hello World!")</syntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<syntaxhighlight lang="c">/* gcc Hello_world_Line_printer.c -o Hello_world_Line_printer -lwren -lm */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"

/* C <=> Wren interface functions */

void C_lprint(WrenVM* vm) {
const char *arg = wrenGetSlotString(vm, 1);
char command[strlen(arg) + 13];
strcpy(command, "echo \"");
strcat(command, arg);
strcat(command, "\" | lp");
system(command);
}

WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "C") == 0) {
if (isStatic && strcmp(signature, "lprint(_)") == 0) return C_lprint;
}
}
return NULL;
}

static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}

char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}

int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.bindForeignMethodFn = &bindForeignMethod;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "Hello_world_Line_printer.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>


=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
<lang asm>;Assemble with: tasm, tlink /t
<syntaxhighlight lang="asm">;Assemble with: tasm, tlink /t
;assume direction bit is clear (so si increments)
;assume direction bit is clear (so si increments)
.model tiny
.model tiny
Line 1,013: Line 1,254:


msg db "Hello World!", 0ch, 0 ;0ch = form feed (for laser printer)
msg db "Hello World!", 0ch, 0 ;0ch = form feed (for laser printer)
end start</lang>
end start</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code Text=12;
<syntaxhighlight lang="xpl0">code Text=12;
Text(2, "Hello World!
Text(2, "Hello World!
");</lang>
");</syntaxhighlight>


The 2 directs the output to the printer (LPT1).
The 2 directs the output to the printer (LPT1).

Latest revision as of 16:17, 9 December 2023

Task
Hello world/Line printer
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Cause a line printer attached to the computer to print a line containing the message:   Hello World!


Note

A line printer is not the same as standard output.

A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper.

With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).

11l

Translation of: Python
V lp = File(‘/dev/lp0’, ‘w’)
lp.write("Hello World!\n")
lp.close()

360 Assembly

HELLO    CSECT
         PRINT NOGEN
         BALR  12,0
         USING *,12
         OPEN  LNPRNTR
         LA    6,HW
         PUT   LNPRNTR
         CLOSE LNPRNTR
         EOJ
LNPRNTR  DTFPR DEVADDR=SYSLST,IOAREA1=L1
L1       DS    0CL133
HW       DC    C'Hello World!'
         END HELLO

Action!

Proc Main()
 Open(1,"P:",8,0)
 PrintDE(1,"HELLO WORLD!")
 Close(1)
Return

Ada

Unix

Assuming that the line printer is attached to /dev/lp0

with Ada.Text_IO; use Ada.Text_IO;

procedure Print_Line is
   Printer : File_Type;
begin
   begin
      Open (Printer, Mode => Out_File, Name => "/dev/lp0");
   exception
      when others =>
         Put_Line ("Unable to open printer.");
         return;
   end;

   Set_Output (Printer);
   Put_Line ("Hello World!");
   Close (Printer);
end Print_Line;

ALGOL 68

This task is VERY system and hardware dependent. The code below works with Algol 68 Genie and a Linux system without /dev/lp0 but with a remote printer interfaced via CUPS. Extending it to other environments is left as an exercise for the reader.

BEGIN
   STRING printer name = "/dev/lp0";
   FILE line printer;
   IF open (line printer, printer name, stand out channel) = 0 THEN
      put (line printer, ("Hello world", newline));
      close (line printer)
   ELSE
      put (stand error, ("Can't contact line printer on ", printer name, newline));
      put (stand error, ("Trying to use lpr(1)", newline));
      PIPE printer pipe = execve child pipe ("lpr", "", "");
      IF pid OF printer pipe < 0 THEN
	 put (stand error, ("Oh dear, that didn't seem to work either.  Giving up.", newline));
	 stop
      FI;
      put (write OF printer pipe, ("Hello world", newline));
      close (read OF printer pipe);
      close (write OF printer pipe)
   FI
END
Output:
Can't contact line printer on /dev/lp0
Trying to use lpr(1)

Applesoft BASIC

Assumes a printer card is installed in the Apple II's number 1 expansion slot.

PR#1
PRINT "HELLO WORLD!"

Arturo

write "/dev/lp0" "Hello World\n"

AutoHotkey

Fileappend, Hello World!, print.txt
Run, print "print.txt"

AWK

Unix / Linux:

BEGIN { print("Hello World!") >"/dev/lp0" }

BASIC

Works with: GW-BASIC
Works with: QBasic
Works with: MSX BASIC
Works with: ZX Spectrum Basic
Works with: Liberty BASIC
LPRINT "Hello World!"

BaCon

Piping data to lp would also work. This example demonstrates writing to a device.

' Hello, printer
READ msg$
DATA "Hello World!\n"

' Assume printer is on /dev/lp0
OPEN "/dev/lp0" FOR DEVICE AS printer
PUTBYTE msg$ TO printer SIZE LEN(msg$)
CLOSE DEVICE printer

BASIC256

printeron
font "Arial", 20, 50
text 10,100, "Hello World!"
printeroff

BBC BASIC

      prn% = OPENOUT("PRN:")
      PRINT #prn%, "Hello World!"
      CLOSE #prn%

GW-BASIC

Works with: BASICA
Works with: PC-BASIC
Works with: QBasic
LPRINT "Hello World!"

IS-BASIC

LPRINT "Hello World!"

MSX Basic

LPRINT "Hello World!"

True BASIC

OPEN #1: PRINTER                  !Open channel #1 for the printer
PRINT #1: "Hello World!"
END

Yabasic

open window 100,100
open printer
text 10, 50, "Hello World!"
close printer
close window

Batch File

ECHO Hello world!>PRN

C

Unix

Assuming that the line printer is attached to /dev/lp0

#include <stdio.h>

int main()
{
   FILE *lp;
   lp = fopen("/dev/lp0","w");
   fprintf(lp,"Hello world!\n");
   fclose(lp);
   return 0;
}

C#

"My Printer" should be replaced with the friendly name of the printer. This is to avoid the extra step of locating the default printer, which is out of scope of this example.

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class DOCINFOA
{
    [MarshalAs(UnmanagedType.LPStr)]
    public string pDocName;
    [MarshalAs(UnmanagedType.LPStr)]
    public string pOutputFile;
    [MarshalAs(UnmanagedType.LPStr)]
    public string pDataType;
}

[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool StartPagePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool EndPagePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool EndDocPrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool ClosePrinter(IntPtr hPrinter);

[DllImport("winspool.Drv", EntryPoint = "WritePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

public void HelloWorld()
{
    IntPtr hPrinter;
    bool openSuccessful = OpenPrinter("My Printer", out hPrinter, IntPtr.Zero);
    if (openSuccessful)
    {
        DOCINFOA docInfo = new DOCINFOA();
        docInfo.pDocName = "Hello World Example";
        docInfo.pOutputFile = null;
        docInfo.pDataType = "RAW";

        if (StartDocPrinter(hPrinter, 1, docInfo))
        {
            StartPagePrinter(hPrinter);

            const string helloWorld = "Hello World!";
            IntPtr buf = Marshal.StringToCoTaskMemAnsi(helloWorld);

            int bytesWritten;
            WritePrinter(hPrinter, buf, helloWorld.Length, out bytesWritten);

            Marshal.FreeCoTaskMem(buf);
        }
        if (EndPagePrinter(hPrinter))
            if (EndDocPrinter(hPrinter))
                ClosePrinter(hPrinter);
    }
}

C++

#include <iostream>
#include <fstream>

int main(){
  std::ofstream lprFile;
  lprFile.open( "/dev/lp0" );
  lprFile << "Hello World!\n";
  lprFile.close();
  return 0;
}

Clipper

SET PRINT ON
SET CONSOLE OFF
? "Hello World!"
SET PRINT OFF
SET CONSOLE ON

Clojure

Translated from Java (mechanically, as I don't understand how to test a line printer):

(ns rosetta-code.line-printer
  (:import java.io.FileWriter))

(defn -main [& args]
  (with-open [wr (new FileWriter "/dev/lp0")]
    (.write wr "Hello, World!")))

COBOL

IDENTIFICATION DIVISION.
PROGRAM-ID. GOODBYE-WORLD-PRINTER.

PROCEDURE DIVISION.
DISPLAY 'Hello World!'
	UPON PRINTER
END-DISPLAY.
STOP RUN.

Commodore BASIC

Most Commodore printer peripherals operate off the IEC bus commonly as device 4 or 5. It is also possible that some printers may be connected through the RS-232 serial port (typically device 2). This example assumes a device on the IEC bus with a default setting of device 4. This example does not utilize any printer control codes to change font, pitch, quality, graphics, etc., as those can vary between brands and models of printer.

10 rem rosetta code - "Hello World" on line printer
20 open 7,4 : rem open <logical file number>, <device number>
30 print#7,"hello world!" : rem print line as shown to logical file number
40 close 7 : rem close the file number


Common Lisp

Assuming that the line printer is attached to /dev/lp0

(defun main ()
  (with-open-file (stream "/dev/lp0"
    :direction :output
    :if-exists :append)
    (format stream "Hello World~%")))
(main)

D

import std.stdio;

void main()
{
    auto lp = File("/dev/lp0", "w");
    lp.writeln("Hello World!");
}

Delphi

program Project1;

{$APPTYPE CONSOLE}

uses Printers;

var
  lPrinterAsTextFile: TextFile;
begin
  AssignPrn(lPrinterAsTextFile);
  Rewrite(lPrinterAsTextFile);
  Writeln(lPrinterAsTextFile, 'Hello World!');
  CloseFile(lPrinterAsTextFile);
end.

Diego

Once the caller has met the computer and its printer...

with_computer(comp1)_printer(lp1)_text(Hello World!);

If the caller is the computer...

with_printer(lp1)_text(Hello World!);

Dragon

select "files"

f2 = fopen("E:\my.txt", "w")
f = "my data"
writeText(f2,f)
flush(f2)
fclose(f2)

EchoLisp

EchoLisp supports a virtual printer which is not stdout. It is actually an extensible division of the HTML document, with printer pages as subdivisions. Printer and pages may be hidden/shown at convenience.

(printer-font "Courier")       ;; change printer font
(printer-page "ROSETTA CODE")  ;; starts a new page with nice header
(printer-writeln "Hello World!") ;; prints new line (not seen on stdout)

EDSAC order code

This program uses self-modifying code to loop through an array of characters. Since the EDSAC character set does not include lower-case letters or exclamation marks, we actually print HELLO WORLD followed by a carriage return and a line feed. Strings cannot be null-terminated, because 0 happens to be the character code for P; instead, we mark the final character by including a 1 (which has no printable effect) in the least significant bit.

[ Hello world
  ===========

  A program for the EDSAC

  Can be used to print any character string:
  the string (including necessary *F and #F
  characters) should be stored in sequential
  memory addresses beginning at @+17.

  The last character of the string should be
  marked with a 1 in the least significant
  bit. This can be coded by using D in place
  of F, e.g. AD would be an 'A' as the last
  character

  Works with Initial Orders 2 ]

        T56K
        GK

[  0 ]  O17@    [ Print character        ]

[  1 ]  H17@    [ AND character with 1:  ]
        C15@    [ if the result is 1, we ]
        S15@    [ have reached the end   ]
        E13@    [ of the string          ]

        T14@    [ Modify the orders in   ]
        A@      [ addresses @+0 and @+1  ]
        A16@    [ to point to the next   ]
        T@      [ character              ]
        A1@
        A16@
        T1@
        E@

[ 13 ]  ZF

[ 14 ]  PF
[ 15 ]  PD
[ 16 ]  P1F     [ NB Least significant bit
                  is not part of address,
                  so add 2 not 1         ]

[ 17 ]  *F      [ Letter shift           ]
        HF
        EF
        LF
        LF
        OF
        !F      [ Blank                  ]
        WF
        OF
        RF
        LF
        DF
        @F      [ Carriage return        ]
        &D      [ Line feed + 1          ]

        EZPF

Alternative

As noted, null in the sense of zero cannot be used as a string terminator on EDSAC. However, it is possible to use the EDSAC null, whose 5-bit code is 10000. The subroutine below demonstrates this.

After the string characters, the terminating null is also sent to the teleprinter. This is because the teleprinter had a one-character buffer, so that an O order did not print its own character immediately, but stored it in the buffer and printed the character set up by the previous O order (Wilkes, Wheeler & Gill, 1951 edition, page 50). Sending the terminating null to the teleprinter ensures that the last character of the string is printed at the same time as the rest.

The EDSAC PC simulator allows .F for null and *F for letter shift, but it seems from WWG that on the original EDSAC these had to be input as K4096F and K2048F respectively.

[Alternative "Hello World" for Rosetta Code]

[Subroutine to print a string.]
[Parameter: A order for first character follows subroutine call (G order).]
[Modified 2022-07-13: A order for first character was formerly passed in 0F.]
[String is terminated with EDSAC null, which is printed]
            T56K GK   [load at 56; set relative addressing]
            A18@ U17@ [plant return link, increasing address by 3
                         instead of 2 as usual]
            S19@      [make A order to load A order after subroutine call]
            T4@       [plant in code]
      [4]   AF        [(planted) load A order after subroutine call]
      [5]   T6@       [loop: plant A order for next character]
      [6]   AF        [load next character]
            UF        [to 0F for printing; keep it in acc]
            OF        [output to teleprinter]
            E12@      [if char >= 0, not EDSAC null]
            A20@      [if char < 0, add 15 to test for EDSAC null]
            G16@      [jump to exit if null]
     [12]   TF        [clear acc]
            A6@ A2F   [inc address in A order above]
                        G5@       [loop back, because top 5 bits = A = 11100]
     [16]   TF        [clear acc on exit (EDSAC convention)]
     [17]   ZF        [(planted) jump back to caller]
     [18]   U3F       [constant for making return link]
     [19]   U1F       [constant for picking up parameter]
     [20]   K2048F    [constant for testing final null]

[Main routine]
            T96K GK   [load at 96; set relative addressing
[Enter with acc = 0]
      [0]   A@ G56F   [call print subroutine]
            A4@       [A order for first character of string]
            ZF        [subroutine returns here; halt machine]
      [4]   K2048F HF EF LF LF OF !F WF OF RF LF DF @F &F K4096F
[The above string is: letter shift, 'HELLO WORLD', CR, LF, null]
            EZ        [define entry point]
            PF        [acc = 0 on entry]
[end]

ERRE

! Hello World in ERRE language
PROGRAM HELLO
BEGIN
  !$REDIR
  PRINT("Hello World !")
  !$NOREDIR
END PROGRAM

Prints on LPT1: (if exists) without opening a file. Note: !$... is a directive pragma not a part of the language.

Factor

Prints through Unix "lpr" command.

( scratchpad ) USE: io.encodings.utf8
( scratchpad ) USE: io.launcher
( scratchpad ) "lpr" utf8 [ "Hello World!" print ] with-process-writer

Forth

Forth systems currently run on everything from bare metal to modern multi-user operating systems and printers are handled differently on each. This demonstration shows a common way that text output is re-directed to printers and/or other devices by vectoring the action of the Forth word EMIT. Emit takes one character off the stack and outputs it to a device. By defining all I/O with the primitive operation EMIT, we can vector the output anywhere we choose, even on hardware with no O/S. Here we show a very basic printer device driver for an embedded system that adds I/O re-direction to the system's Forth language.

\ No operating system, embedded device, printer output example

defer emit                                   \ deferred words in Forth are a place holder for an 
                                             \ execution token (XT) that is assigned later.
                                             \ When executed the deferred word simply runs that assigned routine 

: type ( addr count -- )                     \ type a string uses emit
       bounds ?do  i c@ emit   loop ;        \ type is used by all other text output words in the system

HEX 
: CR   ( -- )  0A emit 0D emit ;             \ send a carriage return, linefeed pair with emit

\ memory mapped I/O addresses for the printer port
B02E   constant scsr                         \ serial control status register 
B02F   constant scdr                         \ serial control data register

: printer-emit ( char -- )                   \ output 'char' to the printer serial port  
         begin   scsr C@ 80 and  until       \ loop until the port shows a ready bit
         scdr C!                             \ C! (char store) writes a byte to an address
         20 ms ;                             \ 32 mS delay to prevent over-runs

: console-emit ( char -- )   ...             \ defined in the Forth system, usually assembler

\ vector control words
: >console     ['] console-emit is EMIT ;     \ assign the execution token of console-emit to EMIT
: >printer     ['] printer-emit is EMIT ;     \ assign the execution token of printer-emit to EMIT

Usage Examples:

S" Hello Console World!" TYPE CR              \ default output goes to console
S" Hello Printer World!" >PRINTER TYPE CR     \ re-direct to printer
>CONSOLE                                      \ return output to console  

Fortran

Fortran I/O statements refer to logical unit numbers to select the file. The device associated with a unit number depends on the computer installation, and can also be arranged via instructions to the operating system. A value such as 6 is often the default for the lineprinter on mainframe systems but on PCs it might be for the computer screen. Thus the "6". The "1" is the label number of the FORMAT statement.

Output to the lineprinter has a "carriage control character" as the first output position, thus a lineprinter capable of 120 characters to a line would be fed up to 121 characters of output, the first printing position (column one on the lineprinter output) would receive the second character of the output, and so on. This could cause surprises. A FORMAT (I6,etc) rather than FORMAT(1X,I5,etc) used to print a five-digit integer at the start of a line (with the leading space being supplied by the first of the six supplied by I6) works well and saves a little on the complexity of the format statement, but if the integer's value were to exceed 99999, say be 100000, the first character is no longer a space but a one, and so the output will suddenly be one line to a page...

The protocol was to act on the carriage control, then print the line. The character code interpretations were

+ No movement - thus overprint.
  (a blank) Advance one line.
0 Advance two lines - thus leave a blank line.
1 Page throw.

The page-throw was actually a "skip to control column 1"; that is, the lineprinter has an associated paper tape in a loop with holes punched in certain columns of the tape and the tape would be advanced one position for each line advance. The length of the loop matches the number of lines to a page of printout, or was twice that number, etc. A hole in column one of the loop would be aligned (by the human operator during setup) with the top-of-form paper position and when a carriage control of "1" was acted on, the lineprinter would skip forwards until the "1" hole was detected. A carriage control character of "2" would thus skip onwards until a hole in column two was detected - and if there was no such hole, the skip wouldn't stop until the human operator noticed. Thus, many control tapes had all columns punched across, not just one. However, this ability was more properly used in producing vast outputs with subsections to a page suitably marked by suitable holes. The benefit was firstly that the printer skipped to a hole mark more rapidly than via a sequence of "advance one" or "advance two" commands, and secondly, the program did not need to generate such sequences nor have then saved via output spooling. But all relied on the right output being matched to the right tape. This was more typical at COBOL installations.

It is because of the first character disappearing as carriage control that the "list" style output (as in WRITE (6,*) "Hello World!") always starts a line of output with a space. This form does not require a FORMAT statement.

Since for a new job, output would commence with the lineprinter already at the top of a new page, an overprint (no carriage advance) thus means writing to the very first line. If however, top-of-page placement was not assured at your installation, then "1HELLO WORLD!" would do.

      WRITE (6,1)
    1 FORMAT ("+HELLO WORLD!")
      END

FreeBASIC

' FB 1.05.0 Win64

Open Lpt "Lpt:" As #1 '' prints to default printer
Print #1, "Hello World!"
Close #1

FutureBasic

The legacy lprint statemenet sends a line of text to the printer. The @(col,row) and %(h,v) options specify where on the page the line should be printed (see the print statement); if you don't specify one of these, the line is printed at the current pen position, usually just under the previously-printed line. lprint is inefficient if you are printing many lines to a page because it reroutes the output each time lprint is executed. In such cases, it's better to execute a sequence of print statements, with the entire sequence preceded by a single route _toPrinter statement and followed by a single route _toScreen statement. FB progammers today use much more sophisticated printer functions designed for complex pagination.

// lprint [@(col,row)|%(h,v)] "Hello,World!"
lprint "Hello,World!"
route _toScreen
close lprint

Go

package main

import (
	"fmt"
	"os"
)

func main() {
	lp0, err := os.Create("/dev/lp0")

	if err != nil {
		panic(err)
	}

	defer lp0.Close()

	fmt.Fprintln(lp0, "Hello World!")
}

Groovy

new File('/dev/lp0').write('Hello World!\n')

GUISS

Start,Programs,Accessories,Notepad,Type:Goodbye World[pling],
Menu:File,Print,Button:OK

Harbour

SET PRINT ON
SET CONSOLE OFF
? "Hello World!"
SET PRINT OFF
SET CONSOLE ON

Haskell

import System.Process (ProcessHandle, runCommand)

main :: IO ProcessHandle
main = runCommand "echo \"Hello World!\" | lpr"

Icon and Unicon

Works in both languages, provided printer is attached to /dev/lp0.

procedure main()
    write(open("/dev/lp0","w"),"Hello, world!")
end

Integer BASIC

See Applesoft BASIC.

J

require'print'
print'Hello world!'

Java

import java.io.FileWriter;
import java.io.IOException;
 
public class LinePrinter {
  public static void main(String[] args) {
    try {
      FileWriter lp0 = new FileWriter("/dev/lp0");
      lp0.write("Hello World!");
      lp0.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
}

JavaScript

Works with: Node.js
// This example runs on Node.js
var fs = require('fs');
// Assuming lp is at /dev/lp0
var lp = fs.openSync('/dev/lp0', 'w');
fs.writeSync(lp, 'Hello, world!\n');
fs.close(lp);
Works with: Firefox
Works with: Chromium
document.write("Hello World!");
print(); //Opens a dialog.

Joy

"/dev/lp" "w" fopen "Hello World!\n" fputchars fclose.

Julia

lineprinter = Sys.iswindows() ? "LPT3" : "/dev/lp0"
lp = open(lineprinter, "w")
write(lp, "Hello world")

Kotlin

Works with: Ubuntu version 14.04
import java.io.File

fun main(args: Array<String>) {
    val text = "Hello World!\n"
    File("/dev/lp0").writeText(text)
}

Lasso

File_Write: '/dev/lp0', 'Hello world', -FileOverWrite;

Locomotive Basic

10 PRINT #8, "Hello World!"

M2000 Interpreter

We can use printer like a page printer

Printer {
      \\ just change the current layer to Print Page
      \\ Using Layer { } we can change to basic console layer inside any layer
      Print "Hello World!"
}

Or we can use ANSI output using a file for export in Lpt1

Try ok {
      Open "Lpt1" For OutPut As N '' prints to Lpt1 if exist a printer 
      Print #N, "Hello World!"
      Close #N
}
If Not Ok Then Print "Can't Print"

If we have a file in current dir we can use a Dos command:

Dos "Print /d:lpt1 file " +quote$(dir$+"this.txt");

Using ; at the end of DOS command we have no open terminal

Dos "command" [, sleep time after call] [;]

Maple

lprint("Hello World!")

Mathematica / Wolfram Language

commandstring = "echo Hello World!  | lpr -P Printer01"
Run[commandstring]

MATLAB / Octave

Unix

Assuming that the line printer is attached to /dev/lp0

  fid = fopen('/dev/lp0'); 
  fprintf(fid,'Hello World!\n');
  fclose(fid);

MIXAL

LPR	EQU	18
STRING	EQU	2000
	ORIG	3000
START	IOC	0(LPR)
	OUT	STRING(LPR)
	HLT
	ORIG	STRING
	ALF	HELLO
	ALF	 WORL
	ALF	D!
	END	START

N/t/roff

/.ROFF/, being a document formatting language, is especially suited for formatting documents and sending them to printers of nearly all types. In fact, /.ROFF/ has been used to print documents on line printers. To send the output to the line printer, you must compile the source file with the following command on the shell, assuming the source file is file.roff and that the line printer is already setup properly.

nroff -Tlpr file.roff

In this case, you must use NROFF, not TROFF, to compile the source file, as NROFF is better-suited for monospaced, typewriter-style line formatting.

Because /.ROFF/ is a document formatting language, the majority of lines in a typical /.ROFF/ source file is to be textual input. This input is typeset directly onto the output medium. Therefore, the user need not call a procedure to print text to any terminal.

Hello World!

Nim

Assuming that the line printer is attached to /dev/lp0:

var lp = open("/dev/lp0", fmWrite)
lp.writeLine "Hello World"
lp.close()

OCaml

Assuming that the line printer is attached to /dev/lp0

let () =
  let oc = open_out "/dev/lp0" in
  output_string oc "Hello world!\n";
  close_out oc ;;

Oforth

File new("/dev/lp0") dup open(File.WRITE) "Hello world\n" << close

Ol

(define p (open-output-file "/dev/lp0"))
(when p
   (print-to p "Hello world!")
   (close-port p))

OpenEdge/Progress

OUTPUT TO PRINTER.
PUT UNFORMATTED "Hello world!" SKIP.
OUTPUT CLOSE.

Pascal

Works with: Free_Pascal
Library: Printer

Example from the FreePascal documentation:

program testprn;
uses printer;
var i: integer;
    f: text;
begin
  writeln ( 'Test of printer unit' );
  writeln ( 'Writing to lst ...' );
  for i := 1 to 80 do
    writeln ( lst, 'This is line', i, '.' #13 );
  close ( lst );
  writeln ( 'Done.' );
  {$ifdef Unix }
  writeln ( 'Writing to pipe ...' );
  assignlst ( f, '|/usr/bin/lpr −m' );
  rewrite ( f );
  for i:= 1 to 80 do
    writeln ( f, 'This is line ', i, '.'#13 );
  close ( f );
  writeln ( 'Done.' )
  {$endif}
end.

Perl

Assuming that the line printer is attached to /dev/lp0

open O, ">", "/dev/lp0";
print O "Hello World!\n";
close O;

Phix

If you have not got something appropriate attached, this will just hang. Other values you can try, on windows: "AUX", "COM1", "COM2", "LPT1"

integer fn = open(iff(platform()=WIN32?"PRN":"/dev/lp0"),"w")
if fn=-1 then
    puts(1,"some error")
else
    puts(fn,"Hello World!")
    close(fn)
    puts(1,"success!")
end if
{} = wait_key()

PHP

<?php
file_put_contents('/dev/lp0', 'Hello world!');
?>
<?php
fclose(STDOUT);
$STDOUT = fopen('/dev/lp0', 'a');
echo 'Hello world!';
?>

Picat

Works with: Picat
main =>
    Printer = open("/dev/lp0", write),
    println(Printer, "Hello, world!"),
    flush(Printer),
    close(Printer).

PicoLisp

(out '(lpr "-P" "Printer01")
   (prinl "Hello world") )

PL/I

hello: procedure options(main);
   put skip list('Hello world.');
end hello;

PostScript

Technically not really correct, as this has to be sent to the printer directly. It will output Hello world, then, though.

<</PageSize [595 842]>> setpagedevice  % set page size to DIN A4
/Courier findfont                      % use Courier
12 scalefont setfont                   % 12 pt
28 802 moveto                          % 1 cm from the top and left edges
(Hello world) show                     % draw the string

Prolog

Works with: SWI Prolog
:- initialization(main).

main :-
    open("/dev/lp0", write, Printer),
    writeln(Printer, "Hello, world!"),
    flush_output(Printer),
    close(Printer).

PureBasic

Library: PureLPRINT
MyPrinter$ = LPRINT_GetDefaultPrinter()
If LPRINT_OpenPrinter(MyPrinter$)
  If LPRINT_StartDoc("Printing a RC-Task")
    LPRINT_Print(Chr(27) + "E") ; PCL reset for HP Printers
    LPRINT_PrintN("Hello World!")
    LPRINT_NewPage()
    LPRINT_EndDoc()
  EndIf
  LPRINT_ClosePrinter()  
EndIf

Python

Assuming that the line printer is attached to /dev/lp0:

lp = open("/dev/lp0")
lp.write("Hello World!\n")
lp.close()

If the above code gives you the error "IOError: File not open for writing", try:

lp = open("/dev/lp0","w")
lp.write("Hello World!\n")
lp.close()

Racket

#lang racket
(define (print text)
  ;; try lpr first
  (define lpr-exe (find-executable-path "lpr"))
  ;; otherwise use a special file
  (if lpr-exe
    (with-input-from-string (~a text "\n") (λ() (void (system* lpr-exe))))
    (with-output-to-file #:exists 'append
      (case (system-type) [(windows) "PRN"] [else "/dev/lp0"])
      (λ() (displayln text)))))
(print "Hello World!")

Raku

(formerly Perl 6)

my $lp = open '/dev/lp0', :w;
$lp.say: 'Hello World!';
$lp.close;

Or using given to avoid having to write the variable name repeatedly:

given open '/dev/lp0', :w {
    .say: 'Hello World!';
    .close;
}

REXX

There is no direct way for REXX programs to write to the printer, but a shell command could be used.

In DOS (or under Windows):

/*REXX program prints a string to the  (DOS) line printer  via redirection to a printer.*/
$= 'Hello World!'                                /*define a string to be used for output*/
'@ECHO'   $    ">PRN"                            /*stick a fork in it,  we're all done. */

Ring

   lp = fopen("/dev/lp0","w")  fputs(lp,"Hello world!")  fclose(lp)

RPG

Works with: ILE RPG
      Fqsysprt   O    F   80        printer                                 
      C                   except                                            
      C                   seton                                        LR   
      Oqsysprt   E                                                          
      O                                           11 'Hello world'

RPL

"Hello world!" PR1

Ruby

Assumes that lpr command reaches printer.

open("| lpr", "w") { |f| f.puts "Hello World!" }

Run BASIC

 shell$("echo \"Hello World!\" | lpr")

Rust

Unix

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    let file = OpenOptions::new().write(true).open("/dev/lp0").unwrap();
    file.write(b"Hello, World!").unwrap();
}

Salmon

Assuming /dev/lp0 accesses the printer:

open_output_text_file("/dev/lp0").print("Hello World!");

Assuming lpr is a command that prints to a printer:

`echo "Hello World!" | lpr`;

Scala

Library: Scala

All platforms

import java.awt.print.PrinterException
import scala.swing.TextArea

object LinePrinter extends App {
  val (show, context) = (false, "Hello, World!")
  try // Default Helvetica, 12p
    new TextArea(context) {
      append(" in printing.")
      peer.print(null, null, show, null, null, show)
    }
  catch {
    case ex: PrinterException => ex.getMessage()
  }
  println("Document printed.")
}

Unix

Assuming device is attached to lp0

object LinePrinter extends App {
  import java.io.{ FileWriter, IOException }
  {
    val lp0 = new FileWriter("/dev/lp0")
    lp0.write("Hello, world!")
    lp0.close()
  }
}

Scheme

Unix

Assuming device is attached to lp0

(call-with-output-file "/dev/lp0"
  (lambda (printer)
    (write "Hello World!" printer)))

Seed7

Assuming that the line printer is attached to /dev/lp0:

$ include "seed7_05.s7i";
 
const proc: main is func
  local
    var file: lp is STD_NULL;
  begin
    lp := open("/dev/lp0", "w");
    writeln(lp, "Hello world!");
    close(lp);
  end func;

Sidef

Sys.open(\var fh, '>', '/dev/lp0') \
    && fh.say("Hello World!")      \
    && fh.close

Simula

Works with: SIMULA-67
BEGIN
   OUTTEXT("Hello World!");
   OUTIMAGE
END

Slope

(file-append-to "/dev/lp0" "Hello world!")

Smalltalk

Works with: Smalltalk/X

portable (dispatches to one of bellow):

s := PrinterStream defaultPrinter new.
s nextPutLine:'Hello, world'.
s close

Unix

s := PipeStream writingTo:'lpr'.
s nextPutLine:'Hello, world'.
s close.

alternative:

'/dev/lp0' asFilename writingFileDo:[:s |
  s nextPutLine:'Hello, world'.
]

Windows

s := WinPrinterStream new.
s nextPutLine:'Hello, world'.
s close.

SNOBOL4

In SNOBOL4, variables can be associated with input and output files. Assigning a value to an output-associated variable also writes it to the associated output file. (Likewise, accessing a variable associated with an input file returns as its value the next record from the associated input file.) By default, the variable "input" is associated with standard input, and the variable "output" is associated with standard output.

     output = "Hello, world."

You can associate the variable "print" with lpt1 (the default local printer port) using the output() function:

     output(.print,25,"lpt1")
     print = "Hello, world."

Swift

import Foundation

let out = NSOutputStream(toFileAtPath: "/dev/lp0", append: true)
let data = "Hello, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
out?.open()
out?.write(UnsafePointer<UInt8>(data!.bytes), maxLength: data!.length)
out?.close()

Tcl

Unix

exec lp << "Hello World!"
set f [open |lp w]
puts $f "Hello World!"
close $f

Windows

set f [open prn w]
puts $f "Hello World!"
close $f

UNIX Shell

Use one of the following lines.

# Use the default printer queue, with lp(1) or lpr(1).
#  1. The system must have a printer queue.
#  2. The printer queue must understand plain text.
#  3. System V has lp(1). BSD has lpr(1).
#     CUPS has both lp(1) and lpr(1).
#
echo 'Hello World!' | lp
echo 'Hello World!' | lpr

# Use a character device.
#  1. The device must understand plain text.
#  2. You must have write permission for the device.
#  3. Some systems have /dev/lp0, /dev/lp1, ...
#  4. BSD has /dev/lpt0, /dev/lpt1, ... for the parallel ports;
#     and /dev/ulpt0, /dev/ulpt1, ... for the USB printers.
# Note that intermingling can occur if two processes write to the device at the
# same time. Using the print spooler method above avoids this problem,
#
echo 'Hello World!' >/dev/lp0
echo 'Hello World!' >/dev/lpt0
echo 'Hello World!' >/dev/ulpt0

Wisp

Unix

Assuming that the device is attached to lp0

call-with-output-file "/dev/lp0"
  λ : printer
      write "Hello World!" printer

Wren

It is not currently possible to communicate with the printer using Wren-cli. So we need to write a minimal embedded program (no error checking) so the C host can do this for us.

/* Hello_world_Line_printer.wren */

class C {
    foreign static lprint(s)
}

C.lprint("Hello World!")


We now embed this in the following C program, compile and run it.

/* gcc Hello_world_Line_printer.c -o Hello_world_Line_printer -lwren -lm */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wren.h"

/* C <=> Wren interface functions */

void C_lprint(WrenVM* vm) {
    const char *arg = wrenGetSlotString(vm, 1);
    char command[strlen(arg) + 13];
    strcpy(command, "echo \"");
    strcat(command, arg);
    strcat(command, "\" | lp");
    system(command);
}

WrenForeignMethodFn bindForeignMethod(
    WrenVM* vm,
    const char* module,
    const char* className,
    bool isStatic,
    const char* signature) {
    if (strcmp(module, "main") == 0) {
        if (strcmp(className, "C") == 0) {
            if (isStatic && strcmp(signature, "lprint(_)") == 0)  return C_lprint;
        }
    }
    return NULL;
}

static void writeFn(WrenVM* vm, const char* text) {
    printf("%s", text);
}

char *readFile(const char *fileName) {
    FILE *f = fopen(fileName, "r");
    fseek(f, 0, SEEK_END);
    long fsize = ftell(f);
    rewind(f);
    char *script = malloc(fsize + 1);
    fread(script, 1, fsize, f);
    fclose(f);
    script[fsize] = 0;
    return script;
}

int main(int argc, char **argv) {
    WrenConfiguration config;
    wrenInitConfiguration(&config);
    config.writeFn = &writeFn;
    config.bindForeignMethodFn = &bindForeignMethod;
    WrenVM* vm = wrenNewVM(&config);
    const char* module = "main";
    const char* fileName = "Hello_world_Line_printer.wren";
    char *script = readFile(fileName);
    WrenInterpretResult result = wrenInterpret(vm, module, script);
    wrenFreeVM(vm);
    free(script);
    return 0;
}

X86 Assembly

;Assemble with: tasm, tlink /t
;assume direction bit is clear (so si increments)
        .model  tiny
        .code
        org     100h
start:  mov     si, offset msg  ;point to message
        jmp     pr20

pr10:   mov     ah, 0           ;write character to printer
        mov     dx, 0           ;LPT1
        int     17h
pr20:   lodsb                   ;al, ds:[si++]
        cmp     al, 0           ;terminator?
        jne     pr10            ;loop if not
        ret                     ;return to OS

msg     db      "Hello World!", 0ch, 0  ;0ch = form feed (for laser printer)
        end     start

XPL0

code Text=12;
Text(2, "Hello World!
");

The 2 directs the output to the printer (LPT1). Output is usually directed to the console using device code 0 instead.

A carriage return and line feed are normally required to make a line printer actually print. (A laser or inkjet printer may require a form feed.) However, some printers, or printer drivers, have a timeout feature that print even without the CR+LF (or FF). The CR+LF can simply be included in the string as shown. Another method is to include the CR+LF control characters as ^M^J.