Копипаста:Hello, world!

Материал из Lurkmore
Перейти к навигацииПерейти к поиску
ACHTUNG! Опасно для моска!
Министерство здравоохранения Луркмора предупреждает: вдумчивое чтение нижеследующего текста способно нанести непоправимый ущерб рассудку. Вас предупреждали.


«Hello, world!» на разных языках.


Anonymous

Hello world <source> /

/</'Hello, world!/ | вывод + привет мир

\ </source> Простенькая программка, складывающая два числа. <source> / /int/x, y, z\/ | Целый тип + переменные. />/y/x/ | Поочерёдный ввод значений переменных

              |(для ввода в пределах одной строки />/y/x\/).

/z/x/+/y\/ |/z/x/+/y\/= "z := (x + y)", а /z/x/+/y/ = "z := x, + y" /</x/y\/ |/</x/y\/ выводит всё в одной строке, а /</x/y/ в двух разных /</z/ \ </source> Весь исходный код может уместиться в пределах одной строки: <source> / |Если писать код в пределах одной строки, образуются клещи (//), что недопустимо! /</'H/'e/'l/'l/'o/',/' /'n/'e/'w/'f/'a/'g\/char/x/>/x/if/x/'hi\/</'win\/if/x/'wtf?\/</'The is manual for newfag\/else\/</'natribu.org\/

|Равносильно

/</'H/'e/'l/'l/'o/',/' /'n/'e/'w/'f/'a/'g\/ /char/x/ />/x/ /if/x/'hi\ |если x = hi. после условия "/" не ставится

/</'win\/                     |а вот после действий ставится

/if/x/'wtf?\ |если x = wtf

/</'The is manual for newfag\/

/else\ |иначе

/</'natribu.org\/

\ </source> Ради наименьшего удобства в использовании, кол-во букв в названиях всех стандартных процедур, функций и типов не превышает 4 символов.

BAT

<source lang="dos"> @echo off ;традиционная строка любого батника echo Hello, World! </source>

или так

<source lang="dos"> @echo Hello, World! </source>

BASIC

<source lang="qbasic"> 10 PRINT "Hello, World!" </source>

Quick/Turbo BASIC: <source lang="qbasic"> ? "Hello, World!" </source>

InfoBASIC: <source lang="qbasic"> CRT 'Hello, World!' </source>

PureBasic

Консоль: <source lang="purebasic"> OpenConsole() PrintN("Hello, World!") Input() </source> Диалоговое окно: <source lang="purebasic"> MessageRequester("Заголовок", "Hello, World!") </source> Окно: <source lang="purebasic"> OpenWindow(0, 0, 0, 200, 50, "Заголовок", #PB_Window_MinimizeGadget|#PB_Window_ScreenCentered) TextGadget(0, 10, 16, 180, 16,"Hello, World!", #PB_Text_Center) Repeat

 Event = WaitWindowEvent() 

Until Event = #PB_Event_CloseWindow </source>

Fortran 77

На культовом: <source lang="fortran">

     PROGRAM HELLOW
     WRITE(UNIT=*, FMT=*) 'Hello World'
     END

</source>

Ruby

Почти не отличается: <source lang="ruby"> puts 'Hello, World!' </source>

Pawn

<source> print("Hello,World!"); </source>

Python

Похожим образом: <source lang="python"> print "Hello, World!" </source> …или так: <source lang"python"> import __hello__ </source>

А вот в Python 3.0 (aka Py3k, Пузик) — немного по-другому: <source lang="python"> print("Hello, World!") </source>

MS-DOS shell

<source lang="dos"> echo Hello, world! </source>

Rexx

<source> Say 'Hello, world!' </source>

Pascal

<source lang="pascal"> begin

 write('Hello, World!')

end. </source>

Delphi

<source lang="pascal"> {$apptype console} begin

 Writeln('Hello, World!');

end. </source> На WinAPI:

<source lang="pascal"> uses windows; begin

 MessageBox(0,'Hello, World!','Заголовок',0);

end. </source>

На ООП:

<source lang="pascal"> uses windows; {$apptype console} Type

 THelloWorld = class
 procedure ShowMsg();
 procedure PrintMsg();
 end;

Procedure THelloWord.ShowMsg(); begin

 MessageBox(0,'Hello, World!','Заголовок',0);

end;

Procedure THelloWord.PrintMsg(); begin

 WriteLn('Hello, World!');

end;

var

H : THelloWorld;

begin

H := THelloWorld.Create;
H.ShowMsg;
H.PrintMsg;

end. </source>

Ада

<source lang="ada"> with Ada.Text_IO; procedure Hello_World is begin

 Ada.Text_IO.Put_Line ("Hello World");

end Hello_World; </source>

Модула-3

<source lang="modula3"> MODULE Main; IMPORT IO; BEGIN

 IO.Put ("Hello World\n")

END Main. </source>

Visual Basic

<source lang="qbasic"> Sub Main()

  print "Hello, World!"

End Sub </source> А в VBA по-другому, но с окном <source lang="qbasic"> Sub Main()

  MsgBox "Hello, World!"

End Sub </source>

Lotus Script

<source lang="qbasic">

 Messagebox "Hello, World!", MB_OK

</source>

Или так (не самый заметный вариант): <source lang="qbasic">

 Print "Hello, World!"

</source>

Или рядом с LS: <source>

 @Prompt([OK];"";"Hello, World!");

</source>

Ещё на "собаках" (аналог print'а): <source>

 @StatusBar("Hello, World!")

</source>

InstallScript

<source lang="qbasic">

 Messagebox("Hello, World!", MB_OK);

</source>

AutoIT

<source>

 MsgBox(0, "AutoIT Window", "Hello, world!", 0.75)

</source>

C

<source lang="cpp">

  1. include <stdio.h>

int main(void) {

 printf("Hello, World!\n");
 return 0;

} </source> Алсо, совместимо с C++.

Objective-C для Яблочников и GNUstep’а

<source lang="objc">

  1. import <Foundation/Foundation.h>

@interface HelloWorld : NSObject @end @imlementation HelloWorld +load{

 NSLog(@"Hello, World!");
 return;

} @end </source>

C++

<source lang="cpp">

  1. include <iostream>

int main() {

   std::cout << "Hello, World!" << std::endl;
   return 0;

} </source> Чуть более извращённый вариант: <source lang="cpp">

  1. include <iostream>

using namespace std; int main() {

   cout << "Hello, World!" << endl;
   
   return 0;

} </source> Win32 API <source lang="cpp">

  1. include <windows.h>

int WINAPI WinMain (HINSTANCE,HINSTANCE,PSTR,int){ MessageBox(0,"Hello, World","F*ck",0); return 0; } </source>

С++ ООП

<source lang="cpp">

  1. include <iostream>

class World {

   public:
       static int Hello()
       {
    	    std::cout << "Hello, world!" << std::endl;
           return 0;
       }

};

int main() {

   return World::Hello();

} </source> С шаблонами: <source lang="cpp"> class World{};

template <typename T> void Hello(T hello) {

   std::cout << "Hello, " << hello << std::endl;

}

template <class World> void Hello() {

   std::cout << "Hello, world!" << std::endl;

}

int main() {

   Hello<World>();	

} </source> Чудеса КЗ грамматики: <source lang="cpp"> template <typename T> class Hello {

   public: 
       Hello(T hello)
       {
           std::cout << "Hello, " << hello << std::endl;
       }

};

template <> class Hello<class World> {

   public:
       Hello()
       {
           std::cout << "Hello, world!" << std::endl;
       }

};

int main() {

   Hello<World>();

} </source> С наследование <source lang="cpp">

  1. include <iostream>

class AbstractHello {

   public:
       virtual ~AbstractHello(){std::cout << " World!";}
       void Prnt(){std::cout << "Hello";}


};

class ChildHello: public AbstractHello {

   public:
       ~ChildHello(){Prnt();}

};

int main() {

   ChildHello *Obj;
   Obj = new ChildHello;
   delete Obj;

} </source> Просто, чтобы повыёбываться (паттерны) <source lang="cpp"> /*!

* Hello world! application
* 
* \file hello.cpp
*/
  1. include <iostream>
  2. include <vector>
  3. include <algorithm>
  4. include <functional>
  5. include <cassert>

/*!

* Dispay message.
*/

void displayMessage();

/*!

* Sentence type
*
* Type of sentence, used to decide how to terminate sentence.
*/

enum ESentenceType {

   eStatement,
   eExclamation,
   sQuestion,
   eCommand

};

/*!

* Utility class to prevent unintended copying of class instances.
*/

class nonCopyable { protected:

   nonCopyable() {
   }
   ~nonCopyable() {
   }

private:

   nonCopyable(const nonCopyable&);
   const nonCopyable& operator=(const nonCopyable&);

};

/*!

* Utility function to obtain punctuation mark to end sentence
* of specified type.
*/

inline char getPunctionMark(ESentenceType sentenceType) {

   char puncMark = '.';
   switch(sentenceType) {
       case eStatement  : puncMark = '.'; break;
       case eExclamation: puncMark = '!'; break;
       case sQuestion   : puncMark = '?'; break;
       case eCommand    : puncMark = '.'; break;
       default: {
           // should never get here
           assert(false);
       }
   }
   return puncMark;

}

/*!

* Utility class for creation of instances.
*/

template<typename TElem> class Creatable { protected:

   Creatable() {
   }
   virtual ~Creatable() {
       clear();
   }

public:

   static TElem* create() {
       TElem* e = new TElem;
       return e;
   }
   void free() {
       delete this;
   }
   virtual void clear() {
   }

};

template<typename TElem, typename TParam> class CreatableParam { protected:

   CreatableParam() {
   }
   virtual ~CreatableParam() {
   }

public:

   static TElem* create(TParam p) {
       TElem* e = new TElem;
       e->initialize(p);
       return e;
   }
   void free() {
       finalize();
       delete this;
   }
   virtual void initialize(TParam /*p*/) {
   }
   virtual void finalize() {
       clear();
   }
   virtual void clear() {
   }

};

/*!

* Base class for displayable content
*/

class DisplayElem

public nonCopyable {

protected:

   DisplayElem() {
   }
   virtual ~DisplayElem() {
   }

public:

   virtual void display(std::ostream& os) const = 0;

};

/*!

* STL algorithm for displaying elements
*/

class Displayer

public std::unary_function<void, const DisplayElem*> {

private:

   std::ostream& m_os;
   char   m_sep;
   size_t m_count;

public:

   Displayer(std::ostream& os, char sep = '\0')
   : m_os(os)
   , m_sep(sep)
   , m_count(0) {
   }
   ~Displayer() {
   }
   void operator()(const DisplayElem* e) {
       if(('\0' != m_sep) && (0 < m_count)) {
           m_os << m_sep;
       }
       e->display(m_os);
       ++m_count;
   }

};

/*!

* STL algorithm for freeing display elements
*/

template <typename TElem> class Freer

public std::unary_function<void, TElem*> {

public:

   void operator()(TElem* e) {
       e->free();
   }

};

/*!

* Display element for letter.
*
* The letter is the fundamental element: it has no substructure.
*/

class Letter

public DisplayElem

, public CreatableParam<Letter, char> { private:

   char m_ch;

protected:

   /*virtual*/ ~Letter() {
   }

public:

   Letter() : m_ch('\0') {
   }
   void initialize(char ch) {
       m_ch = ch;
   }
   void finalize() {
       m_ch = '\0';
   }
   void display(std::ostream& os) const {
       os << m_ch;
       // no endLetter()
   }

};

/*!

* Display element for word.
*
* A word is a sequence of letters.
*/

class Word

public DisplayElem

, public Creatable<Word> { private:

   std::vector<Letter*> m_letters;

protected:

   /*virtual*/ ~Word() {
       clear();
   }

public:

   Word() {
   }
   void clear() {
       std::for_each(m_letters.begin(), m_letters.end(), Freer<Letter>());
       m_letters.clear();
   }
   void addLetter(Letter* s) {
       m_letters.push_back(s);
   }
   /*virtual*/ void display(std::ostream& os) const {
       std::for_each(m_letters.begin(), m_letters.end(), Displayer(os));
       // no endLetter()
   }

};

/*!

* Display element for sentence.
*
* A sentence is a sequence of words.
*/

class Sentence

public DisplayElem

, public CreatableParam<Sentence, ESentenceType> { private:

   std::vector<Word*> m_words;
   ESentenceType m_sentenceType;

protected:

   /*virtual*/ ~Sentence() {
       clear();
   }
   void endSentence(std::ostream& os) const {
       const char puncMark = getPunctionMark(m_sentenceType);
       os << puncMark;
   }

public:

   Sentence()
   : m_sentenceType(eStatement) {
   }
   void initialize(ESentenceType sentenceType) {
       m_sentenceType = sentenceType;
   }
   void finalize() {
       m_sentenceType = eStatement;
   }
   void clear() {
       std::for_each(m_words.begin(), m_words.end(), Freer<Word>());
       m_words.clear();
   }
   void addWord(Word* w) {
       m_words.push_back(w);
   }
   void display(std::ostream& os) const {
       std::for_each(m_words.begin(), m_words.end(), Displayer(os, ' '));
       endSentence(os);
   }

};

/*!

* Display element for message.
*
* A message is a sequence of sentences.
*/

class Message

public DisplayElem

, public Creatable<Message> { private:

   std::vector<Sentence*> m_sentences;

protected:

   /*virtual*/ ~Message() {
       clear();
   }
   void endMessage(std::ostream& os) const {
       os << std::endl;
   }

public:

   Message() {
   }
   void clear() {
       std::for_each(m_sentences.begin(), m_sentences.end(), Freer<Sentence>());
       m_sentences.clear();
   }
   void addSentence(Sentence* s) {
       m_sentences.push_back(s);
   }
   void display(std::ostream& os) const {
       std::for_each(m_sentences.begin(), m_sentences.end(), Displayer(os, ' '));
       endMessage(os);
   }

};

/*!

* Main entrance point.
*/

int main() {

   displayMessage();
   return 0;

}

/*!

* Display message.
*/

void displayMessage() {

   Word* first_word = Word::create();
   first_word->addLetter(Letter::create('H'));
   first_word->addLetter(Letter::create('e'));
   first_word->addLetter(Letter::create('l'));
   first_word->addLetter(Letter::create('l'));
   first_word->addLetter(Letter::create('o'));
   Word* second_word = Word::create();
   second_word->addLetter(Letter::create('w'));
   second_word->addLetter(Letter::create('o'));
   second_word->addLetter(Letter::create('r'));
   second_word->addLetter(Letter::create('l'));
   second_word->addLetter(Letter::create('d'));
   Sentence* sentence = Sentence::create(eExclamation);
   sentence->addWord(first_word);
   sentence->addWord(second_word);
   Message* message = Message::create();
   message->addSentence(sentence);
   message->display(std::cout);
   message->free();
   // sentences, etc freed by parent

} </source>

C#

<source lang="csharp"> using System;

class Program {

   static void Main()
   {
       Console.Write("Hello, World!");
   }

} </source> или так <source lang="csharp"> class Program {

   static void Main()
   {
       System.Windows.Forms.MessageBox.Show("Hello, World!");
   }

} </source> или даже так, если версия C# >=9.0 <source lang="csharp"> System.Console.Write("Hello, World!"); </source> Или с использованием DI-контейнеров <source lang="csharp"> using System; using Microsoft.Practices.Unity;

class Program {

   static void Main(string[] args)
   {
       var writer = new ConsoleMessageWriter();
       UnityContainer uc = new UnityContainer();
       uc.RegisterType<IMessageWriter, ConsoleMessageWriter>(new ContainerControlledLifetimeManager());
       var salutation = uc.Resolve<Salutation>();
           
       salutation.Exclaim();
   }

}

public interface IMessageWriter {

   void Write(string message);

}

public class ConsoleMessageWriter : IMessageWriter {

   public void Write(string message)
   {
       Console.WriteLine(message);
   }

}

public class Salutation {

   [Dependency]
   public IMessageWriter Writer { get; set; }
   public Salutation() {}
   public void Exclaim()
   {
       Writer.Write("Hello world");
   }

} </source>

F#

<source lang="ocaml"> printfn "Hello, World!" </source>

Boo

<source lang="ocaml"> print("Hello, World!") </source> Или: <source lang="ocaml"> print "Hello, World!" </source> Или даже так: <source lang="ocaml"> System.Console.WriteLine("Hello, World!") </source>

Perl

<source lang="perl">

  1. !/usr/bin/perl

print "Hello, World!\n"; </source> или так: <source lang="bash"> perl -le "print 'Hello, World!';" </source> или вообще так: <source lang="bash"> perl -e 'use feature q/say/; say "Hello, World!"' </source>

Haskell

Так — в весьма простом и довольно красивом, но малопопулярном языке Haskell (обратите внимание на прекрасную читаемость и простоту кода): <source lang="haskell"> {-# LANGUAGE NoImplicitPrelude #-}

import qualified Data.ByteString as BS -- бесполезный импорт. Помог бы автору, но мне тоже лень. import Data.Foldable (foldl1) import Data.Function ((.)) import Text.Show (show) import Data.List ((++)) import Data.Char (Char) import Control.Monad ((>>=)) import System.IO

main :: IO ()

      -- а тут автор был настолько ленив, что использовал один приём 2 раза. Подряд.

main = hSetBuffering stdout NoBuffering >>= \ _ -> hSetBuffering stdin LineBuffering >>= \ _ -> putHelloWorld (message1)

 where 
   message :: Char
   message = [ 'H':'e':'l':'l':'o':',':[], 'w':'o':'r':'l':'d':'!':[] ]
   
   putHelloWorld :: [Char] -> IO () -- putHelloWorld = putStrLn
   putHelloWorld []     = System.IO.hPutStr stdout ('\n':[])
   putHelloWorld (x:xs) = System.IO.hPutStr stdout (x:[]) >>= \ _ -> putHelloWorld xs
   
   message1 = let f = (++) . (++ " "); f1 = foldl1 f
              in  f1 message

</source>

Чуть менее полный матана говнокода вариант на Haskell: <source lang="haskell">

main = putStrLn "Hello, world!"

</source>

LISP

Вообще-то будет так: <source lang="lisp"> (eval (cons (quote mapcar)

           (cons (cons (quote function)
                       (cons (quote princ) ()))
                 (cons (cons (quote quote)
                             (cons (cons #\H (cons #\e (cons #\l (cons #\l (cons #\o 
                                    (cons #\, (cons #\Space 
                                     (cons #\w (cons #\o (cons #\r (cons #\l (cons #\d (cons #\! 
                                      ()))))))))))))) ())) ()))))

</source> Но можно и так: <source lang="lisp"> (mapcar #'princ '(#\H #\e #\l #\l #\o #\, #\Space #\w #\o #\r #\l #\d #\!)) </source> Или так: <source lang="lisp"> (princ "Hello, world!") </source> Алсо в Common Lisp: <source lang="lisp"> (format t "hello world~%") </source> Или даже так (в REPL): <source lang="lisp"> "Hello, world!" </source>

Clojure

<source lang="clojure"> (println "Hello world") </source>

BrainFuck

Нечитаемый вариант: <source> ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. </source> Китайский стиль: <source> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++.+++++++..+++.-------------------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++.+++.------.--------.-------------------------------------------------------------------. </source>

Forth

<source >

HELLO 72 EMIT 101 EMIT 2 0 DO 108 EMIT LOOP 111 EMIT ;
WORLD 119 EMIT 111 EMIT 114 EMIT 108 EMIT 100 EMIT ;
HELLO_WORLD HELLO 44 EMIT SPACE WORLD 33 EMIT ;

HELLO_WORLD </source>

Тот же Forth без выебоновЪ: <source >

HelloWorld ." Hello, world!" ;

</source>

Factor

<source> USE: io IN: hello-world

hello ( -- ) "Hello, world!" print ;

MAIN: hello </source>

1С:Предприятие 7.7/8/8.1/8.2

Так решается эта задача во встроеном языке отечественного производителя 1С: <source> Предупреждение("Hello, world"); </source> Как вариант: <source> DoMessageBox("Hello, world",,"Attention"); </source>

Или так: <source> Сообщить("Привет, Мир!"); </source> Или так: <source> Message("Привет, Мир!", MessageStatus.Attention); </source>

А на 8.2 еще и так можно: <source> Сообщение = Новый СообщениеПользователю; Сообщение.Текст = "Хелло, Ворлд"; Сообщение.Сообщить(); </source> И вот так тоже можно: <source> Message = New User Message; Message.Text = "Хелло, Ворлд"; Message.Message(); </source> ну и вот так еще <source> Вопрос("Хелло, Ворлд!", РежимДиалогаВопрос.ОК); </source>

Java

Кофеиновый код: <source lang="java"> public class HelloWorld {

 public static void main(String[] args) {
   System.out.println("Hello, world!");
 }

} </source> С выебонами: <source lang="java"> //hello class public class HelloWorld extends java.lang.Object {

   //args - arguments from cmd
   public static final void main(java.lang.String[] args) {
       java.lang.System.out.println(new String("Hello, World!"));
   }

} </source>

Та же жаба, с выебонами, зависящая от старого багованного верификатора кода. <source lang="java"> public class HelloWorld {

 static
 {
   System.out.println("Hello, world!");
   System.exit(0);
 }

} </source> Жаба с окном <source lang="java"> public class hw { public static void main (String [] args){ javax.swing.JOptionPane.showMessageDialog(null,"Хэлловорлд!"); } } </source> Жаба с окном, сделанным своими руками <source lang="java"> import java.awt.*; import javax.swing.*; public class HelloWorld extends JFrame{ HelloWorld(){ setVisible (true); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300,300); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(dim.width/2-getSize().width/2,dim.height/2-getSize().width/2); JLabel l = new JLabel("Хэловорлд"); setLayout(null); l.setBounds(110, 110, 70, 20); add(l); } public static void main(String[] args) { new HelloWorld(); } }

</source> Выебоны с паттернами <source lang="java"> public interface Subject {

   public void attach(Observer observer);
   public void detach(Observer observer);
   public void notifyObservers();

}

public interface Observer {

   public void update(Subject subject);

}

public class HelloWorldSubject implements Subject {

   private ArrayList<Observer> observers;
   private String str;
    
   public HelloWorldSubject() {
       super();

       observers = new ArrayList<Observer>();
   }

   public void attach(Observer observer) {
       observers.add(observer);
   }

   public void detach(Observer observer) {
       observers.remove(observer);
   }

   public void notifyObservers() {
       Iterator<Observer> iter = observers.iterator();
        
       while (iter.hasNext()) {
           Observer observer = iter.next();
           observer.update(this);
       }
   }
    
   public String getStr() {
       return str;
   }

   public void setStr(String str) {
       this.str = str;
       notifyObservers();
   }

}

public class HelloWorldObserver implements Observer {

   public void update(Subject subject) {
       HelloWorldSubject sub = (HelloWorldSubject)subject;
       System.out.println(sub.getStr());
   }

}

public interface Command {

   void execute();

}

public class HelloWorldCommand implements Command {

   private HelloWorldSubject subject;
    
   public HelloWorldCommand(Subject subject) {
       super();
    
       this.subject = (HelloWorldSubject)subject;
   }
    
   public void execute() {
       subject.setStr("hello world");
   }

}

public interface AbstractFactory {

   public Subject createSubject();
   public Observer createObserver();
   public Command createCommand(Subject subject);

}

public class HelloWorldFactory implements AbstractFactory {

   public Subject createSubject() {
       return new HelloWorldSubject();
   }

   public Observer createObserver() {
       return new HelloWorldObserver(); 
   }

   public Command createCommand(Subject subject) {
       return new HelloWorldCommand(subject);
   }

}

public class FactoryMakerSingleton {

   private static FactoryMakerSingleton instance = null;
   private AbstractFactory factory;

   private FactoryMakerSingleton() {
       factory = new HelloWorldFactory();
   }
    
   public static synchronized FactoryMakerSingleton getInstance() {
       if (instance == null) {
           instance = new FactoryMakerSingleton();
       }
        
       return instance;
   }

   public AbstractFactory getFactory() {
       return factory;
   }

}

public class AbuseDesignPatterns {

   public static void main(String[] args) {
       AbstractFactory factory = FactoryMakerSingleton.getInstance().getFactory();
        
       Subject subject = factory.createSubject();
       subject.attach(factory.createObserver());
        
       Command command = factory.createCommand(subject);
        
       command.execute();
   }

} </source>

Scala

<source lang="scala"> object HelloWorld extends App {

 println("Hello, world!")

} </source>

ActionScript 2.0

<source lang="ecmascript">traсe ("hello world!");</source>

ActionScript 3.0

<source lang="ecmascript">traсe ("hello world!");</source> Или так: <source> var field:TextField=new TextField(); field.text="hello world!"; addChild(field); </source>

Eiffel

<source lang="eiffel"> class HELLO_WORLD feature

 print_hello is
     -- Print "Hello, World!"
   do
     print ("Hello, World!")
   end

end </source>

MIDlet Pascal

<source lang="pascal"> Program Hello; Begin

 DrawText('Hello, world!', 5, 5);
 Repaint; Delay(5000);

End. </source>

PHP

<source lang="php"> echo "Hello, world!"; </source> Или так (при вставке кода в HTML): <source lang="php"> <?="Hello, world!"?> </source>

Или с использованием ОО-паттернов программирования: <source lang="php"> /******************************************************************** Model-View-Controller implementation according to POSA (Pattern-Oriented Software Architecture

 http://www.hillside.net/patterns/books/Siemens/book.html)
                                                                                                                                        • /

class HelloWorldController {

   private $model;
   function __construct($model) {
       $this->model = $model;
   }

   function handleEvent($args) {
       $this->model->setStrategy($args[2]);
       $this->model->addText($args[1]);
   }

}


class HelloWorldModel {

   private $text;
   private $observers = array();
   private $strategy;
   
   function attach($observer) {
       $this->observers[] = $observer;
   }

   function getData() {
       $facade = new HelloWorldFacade($this->strategy);
       return $facade->getHelloWorld().$this->text."\n";
   }

   function addText($text=) {
       $this->text = $text;
       $this->notify();
   }

   function setStrategy($strategy) {
       $this->strategy = $strategy;
   }
   
   function notify() {
       foreach ($this->observers as $observer) {
           $observer->update();
       }
   }

}

class HelloWorldView {

   private $model;

   function initialize($model) {
       $this->model = $model;
       $model->attach($this);
       return $this->makeController();
   }

   function makeController() {
       return new HelloWorldController($this->model);
   }

   function update() {
       $this->display();
   }

   function display() {
       echo $this->model->getData();
   }

}


/********************************************************************* "Business logic"

                                                                                                                                        • /

class HelloWorld {

  function execute() {
      return "Hello world";
  }

}

class HelloWorldDecorator {

  private $helloworld;
  function __construct($helloworld) {
      $this->helloworld = $helloworld;
  }

  function execute() {
      return $this->helloworld->execute();
  }

}

abstract class HelloWorldEmphasisStrategy {

   abstract function emphasize($string);

}

class HelloWorldBangEmphasisStrategy extends HelloWorldEmphasisStrategy {

   function emphasize($string) {
      return $string."!";
   }

}

class HelloWorldRepetitionEmphasisStrategy extends HelloWorldEmphasisStrategy {

   function emphasize($string) {
      return $string." and ".$string." again";
   }

}

class HelloWorldEmphasizer extends HelloWorldDecorator {

  private $strategy;
  function HelloWorldEmphasizer($helloworld,$strategy) {
      $this->strategy = $strategy;
      parent::__construct($helloworld);
  }

  function execute() {
      $string = parent::execute();
      return $this->strategy->emphasize($string);
  }

}

class HelloWorldStrategyFactory {

   static function make($type) {
       if ($type == 'repetition') return self::makeRepetitionStrategy();
       return self::makeBangStrategy();
   }

   static function makeBangStrategy() {
       return new HelloWorldBangEmphasisStrategy;
   }
   static function makeRepetitionStrategy() {
       return new HelloWorldRepetitionEmphasisStrategy;
   }

}

class HelloWorldFormatter extends HelloWorldDecorator {

  function execute() {
      $string = parent::execute();
      return $string."\n";
  }

}

class HelloWorldFacade {

   private $strategy;
   function __construct($strategyType) {
       $this->strategy = HelloWorldStrategyFactory::make($strategyType);
   }

   function getHelloWorld() {
       $formatter = new HelloWorldFormatter(
               new HelloWorldEmphasizer(
                   new HelloWorld,$this->strategy));
       return $formatter->execute();
   }

}

$model = new HelloWorldModel; $view = new HelloWorldView; $controller = $view->initialize($model); $controller->handleEvent($_SERVER['argv']); </source>

Vbscript

<source lang="vb"> Msgbox "Hello world!" </source>

Javascript

<source lang="javascript"> $=~[];$={___:++$,$$$$:(![]+"")[$],__$:++$,$_$_:(![]+"")[$],_$_:++$,$_$$:({}+"")[$],$$_$:($[$]+"")[$],_$$:++$,$$$_:(!""+"")[$],$__:++$,$_$:++$,$$__:({}+"")[$],$$_:++$,$$$:++$,$___:++$,$__$:++$};$.$_=($.$_=$+"")[$.$_$]+($._$=$.$_[$.__$])+($.$$=($.$+"")[$.__$])+((!$)+"")[$._$$]+($.__=$.$_[$.$$_])+($.$=(!""+"")[$.__$])+($._=(!""+"")[$._$_])+$.$_[$.$_$]+$.__+$._$+$.$;$.$$=$.$+(!""+"")[$._$$]+$.__+$._+$.$+$.$$;$.$=($.___)[$.$_][$.$_];$.$($.$($.$$+"\""+$.$$_$+$._$+$.$$__+$._+"\\"+$.__$+$.$_$+$.$_$+$.$$$_+"\\"+$.__$+$.$_$+$.$$_+$.__+".\\"+$.__$+$.$$_+$.$$$+"\\"+$.__$+$.$$_+$._$_+"\\"+$.__$+$.$_$+$.__$+$.__+$.$$$_+"(\\\"\\"+$.__$+$.__$+$.___+$.$$$_+(![]+"")[$._$_]+(![]+"")[$._$_]+$._$+", \\"+$.__$+$.$$_+$.$$$+$._$+"\\"+$.__$+$.$$_+$._$_+(![]+"")[$._$_]+$.$$_$+"!\\\")\\"+$.$$$+$._$$+"\"")())(); </source> Или вот так (не работает, когда броузер парсит страницу как XHTML, то есть в далеком будущем, когда сервера начнут отдавать страницы с MIME-типом application/xhtml+xml) <source lang="javascript"> document.write("Hello, world!"); </source>

Или так ("классы")

(function() {
   function Chatterbox(msg) {
      this.msg = msg || 'Hello, world!';
   }
       
   Chatterbox.prototype.greet = function() {
      alert(this.msg);
   }
       
   var chatter = new Chatterbox();
   chatter.greet();
})();


Или вот так (окно с сообщением) <source lang="javascript"> alert("Hello, world!"); </source>

В NodeJS (распечатает в командную строку) а в браузере(в отладчик в консоль): <source lang="javascript"> console.log("Hello, world!"); </source>

Или вот так на Action script 3.0 (флэшовая реализация стандарта ECMAScript): <source lang="javascript">

trace('Hello World!');

//Или, если непременно надо вывести прямо на экран, а не в консоль, так: var tf:TextField = new TextField; tf.text = "Hello World!"; addChild(tf); </source> Или если ООП: <source lang="javascript"> package {

 import flash.display.Sprite;
 public class HelloWorld extends Sprite {
   public function HelloWorld() {
     trace ("Hello, world!");
   }
 }

} </source>

Теперь оно и сервер-сайд! <source lang="javascript">

  1. !/usr/bin/env node

var http = require('http'); http.createServer(function (req, res) {

 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end('Hello World\n');

}).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); </source>

sh

<source lang="bash"> echo Hello, world! </source>

Или так <source lang="bash"> cat <<EOF Hello world! EOF </source>

Индусский вариант <source lang="bash"> for i in 'H' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'l' 'd' '!' '\n'; do

       echo -ne "$i"

done </source>

На bash.orge

http://bash.org.ru/?text=Hello+world

На Прологе

<source> goal :-

 write ("Hello, World!").

</source>

SQL запрос

SQL-92

<source lang="sql"> select 'Hello, World!' </source>

Oracle SQL

<source lang="sql"> select 'Hello, World!' from dual; </source>

Oracle PL/SQL

<source lang="sql"> SET serveroutput ON

BEGIN

dbms_output.put_line('Hello world!');

END; / </source>

PostgreSQL

<source lang="sql"> select 'Hello, World!'; </source>

PostgreSQL PL/pgSQL

<source lang="sql"> DO $$ BEGIN

  RAISE NOTICE 'Hello world!';

END; $$; / </source>

T-SQL (Microsoft SQL Server)

<source> PRINT 'Hello, world'; </source>

MySQL

<source lang="sql"> select 'Hello, World!'; </source>

FireBird SQL / InterBase

<source lang="sql"> select 'Hello, World!' FROM RDB$DATABASE; </source>

Informix

<source lang="sql"> SELECT FIRST 1 'Hello, World!' FROM systables; </source>

Обычно хеллоуворлдщика можно ввести в транс, добавив в какой-нибудь частоиспользуемый header-файл следующие строчки (ахтунг, C-specific!): <source lang="cpp">

  1. ifndef DEFINE_ME
  2. error Fatal error! There must be some brain in your head!
  3. endif

</source>

Ассемблер

Очевидно, что никакой сложности в решении такая задача собой не представляет. Тем не менее, решив подобную задачу на каком-либо языке программирования, субъект чаще всего начинает oшибочно самоидентифицироваться с программистом.

Однако на языках ассемблера данная задача представляется более сложной:


Assembler i8086, MS-DOS, fasm

<source lang="asm"> use16 org 100h

mov ah,09h mov dx,msg int 21h

mov ax,4C00h int 21h msg db 'Hello, World!$' </source>

Assembler i8086, MS-DOS, masm

<source lang="asm"> .model tiny .code org 100h

Start: mov ah, 9 mov dx, offset msg int 21h

mov ax, 4C00H int 21h

msg db 'Hello, world$' end Start </source>

Assembler i8086, MS-DOS, tasm

<source lang="asm"> mov ax, 0b800h mov ds, ax mov [02h], 'H' mov [04h], 'e' mov [06h], 'l' mov [08h], 'l' mov [0ah], 'o' mov [0ch], ',' mov [0eh], 'W' mov [10h], 'o' mov [12h], 'r' mov [14h], 'l' mov [16h], 'd' mov [18h], '!' ret </source>

Assembler i386, Linux, nasm

<source lang="asm"> SECTION .data msg: db "Hello, world",10 len: equ $-msg

SECTION .text global main main: mov edx, len mov ecx, msg mov ebx, 1 mov eax, 4 int 0x80

mov ebx, 0 mov eax, 1 int 0x80 </source>

То же, только GAS

<source lang="asm"> .data msg: .ascii "Hello,world!\n" len = . - msg

.text .globl _start _start: movl $4,%eax movl $1,%ebx movl $msg,%ecx movl $len,%edx int $0x80

xorl %ebx,%ebx movl $1,%eax int $0x80 </source>

AMD64 Linux, GAS

<source lang="asm"> .text prefix: .ascii "Hello, World\n" .set prefix_size, . - prefix .global _start _start: xorq %rax, %rax incb %al xorl %edi, %edi incl %edi movq $prefix, %rsi mov $prefix_size, %edx syscall movl $60, %eax xorl %edi, %edi syscall </source>

Assembler i386, Windows, masm

<source lang="asm"> .386 .model flat, stdcall option casemap:none include \masm32\include\windows.inc include \masm32\include\kernel32.inc includelib \masm32\lib\kernel32.lib

.data msg db "Hello, world!", 13, 10 len equ $-msg

.data? written dd ?

.code start: push -11 call GetStdHandle

push 0 push offset written push len push offset msg push eax call WriteFile

push 0 call ExitProcess end start </source>

Или так: <source lang="asm"> .386 .model flat, STDCALL includelib kernel32.lib GetStdHandle PROTO:DWORD WriteConsoleA PROTO:DWORD,:DWORD,:DWORD,:DWORD,:DWORD ExitProcess PROTO:DWORD .const message db "Hello, world!" .code Main PROC LOCAL hStdOut :DWORD push -11 call GetStdHandle mov hStdOut,EAX push 0 push 0 push 16d push offset message push hStdOut call WriteConsoleA push 0 call ExitProcess Main ENDP End Main </source>

Assembler fasm for Windows

<source lang="asm"> include 'win32ax.inc' s: invoke MessageBox,0,'Хэловорлд',' ',0 .end s </source>

Assembler микроконтроллер ATMega16, AVR Studio

<source lang="asm"> .include "m16def.inc" .cseg .org $0000 rjmp start ;Reset handler .org $0030 start: ldi r24, 25  ; ~= 9600 @ 4Mhz clock out UBRRL, r24 out UBRRH, r2 ldi r24, 1 << TXEN out UCSRB, r24 ldi r24, 1 << URSEL | 1 << UCSZ0 | 1 << UCSZ1 ; 8-n-1 out UCSRC, r24

send msg

ldi ZL, msg << 1 loop: lpm r0, Z+ ; next char tst r0  ; terminated? stop: breq stop

while_busy: sbis UCSRA, UDRE rjmp while_busy out UDR, r0 rjmp loop msg: .db "Hello, world!", 13, 10, 0 </source>

Assembler TASM для ZX Spectrum 48/128

<source lang=>

 ORG #C000

Start:

 LD HL,Text

Loop:

 LD A,(HL)
 XOR A
 RET Z
 RST 16
 INC HL
 JR Loop

Text:

 DB 'Hello, world!
 DB 0

</source>

Машинный код Win32

Это можно вставить в шестнадцатеричный редактор, сохранить с расширением .exe, и оно сразу станет запускаемым под виндой, без всяких компиляторов и ассемблеров. <source> 4D5A000000000000000000001A110000281000000000000000000000000000002F11000030100000211100000000000034110000000000000000000040000000504500004C01010000000000000000000000000070000F010B010000000000000000000000000000F01000000010000000000000000040000010000000020000000000000000000003000A000000000000200000D9000000000000000200000000000000000000000000000000000000000000000200000000000000000000000010000000000000000000000000000000000000001000000100000001000000000000000000000000000000600000E06A006842104000E80E00000048656C6C6F2C20776F726C6421006A00FF15301040006A00FF15281040004B45524E454C3332004578697450726F6365737300555345523332004D657373616765426F784100000000000000 </source> Ниже представлена чуть более читабельная версия. В ASCII-представлении даже можно увидеть что-то человеческое, в частности, выводимую строку, названия функций WinAPI и названия библиотек, в которых они находятся. Сам исполняемый код находится по смещению 0xF0 и занимает 42 байта, включая строку "Hello, world!\0". А вообще, образ построен не по правилам. <source> Offset 0 1 2 3 4 5 6 7 8 9 A B C D E F

00000000 4D 5A 00 00 00 00 00 00 00 00 00 00 1A 11 00 00 MZ 00000010 28 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ( 00000020 2F 11 00 00 30 10 00 00 21 11 00 00 00 00 00 00 / 0  ! 00000030 34 11 00 00 00 00 00 00 00 00 00 00 40 00 00 00 4 @ 00000040 50 45 00 00 4C 01 01 00 00 00 00 00 00 00 00 00 PE L 00000050 00 00 00 00 70 00 0F 01 0B 01 00 00 00 00 00 00 p 00000060 00 00 00 00 00 00 00 00 F0 10 00 00 00 10 00 00  ? 00000070 00 00 00 00 00 00 40 00 00 10 00 00 00 02 00 00 @ 00000080 00 00 00 00 00 00 00 00 03 00 0A 00 00 00 00 00 00000090 00 20 00 00 D9 00 00 00 00 00 00 00 02 00 00 00 U 000000A0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000000B0 00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00 000000C0 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 000000D0 00 00 00 00 00 10 00 00 01 00 00 00 01 00 00 00 000000E0 00 00 00 00 00 00 00 00 00 00 00 00 60 00 00 E0 ` a 000000F0 6A 00 68 42 10 40 00 E8 0E 00 00 00 48 65 6C 6C j hB @ e Hell 00000100 6F 2C 20 77 6F 72 6C 64 21 00 6A 00 FF 15 30 10 o, world! j y 0 00000110 40 00 6A 00 FF 15 28 10 40 00 4B 45 52 4E 45 4C @ j y ( @ KERNEL 00000120 33 32 00 45 78 69 74 50 72 6F 63 65 73 73 00 55 32 ExitProcess U 00000130 53 45 52 33 32 00 4D 65 73 73 61 67 65 42 6F 78 SER32 MessageBox 00000140 41 00 00 00 00 00 00 00 A </source>

На двух семисегментных индикаторах и VHDL

<source lang="cpp"> LIBRARY IEEE; USE IEEE.STD_LOGIC_1164.ALL; USE IEEE.NUMERIC_STD.ALL; USE IEEE.STD_LOGIC_UNSIGNED.ALL;

ENTITY CTL IS PORT( CLK: IN STD_LOGIC; DOUT1: OUT STD_LOGIC_VECTOR(0 TO 6); DOUT2: OUT STD_LOGIC_VECTOR(0 TO 6) ); END ENTITY;

ARCHITECTURE CTL_ARCH OF CTL IS SIGNAL CNT: STD_LOGIC_VECTOR(0 TO 3):="0000";

BEGIN PROCESS(CLK) BEGIN IF (CLK'EVENT AND CLK='1') THEN IF CNT = "1011" THEN CNT <= "0000"; END IF; CASE CNT IS WHEN "0000" => DOUT1 <= "1001000"; DOUT2 <="1111111";--H WHEN "0001" => DOUT1 <= "0110001"; DOUT2 <="1111111";--E WHEN "0010" => DOUT1 <= "1110001"; DOUT2 <="1111111";--L WHEN "0011" => DOUT1 <= "1110001"; DOUT2 <="1111111";--L WHEN "0100" => DOUT1 <= "0000001"; DOUT2 <="1111111";--O WHEN "0101" => DOUT1 <= "1111111"; DOUT2 <="1111111";-- WHEN "0110" => DOUT1 <= "1100001"; DOUT2 <="1000001"; --W(1) W(2) WHEN "0111" => DOUT1 <= "0000001"; DOUT2 <="1111111";--O WHEN "1000" => DOUT1 <= "0011000"; DOUT2 <="1111111";--R WHEN "1001" => DOUT1 <= "1110001"; DOUT2 <="1111111";--L WHEN "1010" => DOUT1 <= "0000001"; DOUT2 <="1111111";--D WHEN OTHERS => DOUT1 <= "1111111"; DOUT2 <="1111111"; END CASE; CNT<= CNT+1; END IF; END PROCESS; END CTL_ARCH; </source>

HQ9+ / HQ9++ / HQ9+/-

<source hq9+> H </source>

C++ с использованием Component Object Model

На мелкомягком быдлоподелии: <source lang=idl> [

   uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820)

] library LHello {

   importlib("actimp.tlb");
   importlib("actexp.tlb");
  1. include "pshlo.idl"
   [
       uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820)
   ]
   cotype THello
   {
       interface IHello;
       interface IPersistFile;
   };

}; [

   exe,
   uuid(2573F890-CFEE-101A-9A9F-00AA00342820)

] module CHelloLib {

   importheader();
   importheader();
   importheader();
   importheader("pshlo.h");
   importheader("shlo.hxx");
   importheader("mycls.hxx");
   importlib("actimp.tlb");
   importlib("actexp.tlb");
   importlib("thlo.tlb");
   [
       uuid(2573F891-CFEE-101A-9A9F-00AA00342820),
       aggregatable
   ]
   coclass CHello
   {
       cotype THello;
   };

}; </source> <source lang=cpp>

  1. include "ipfix.hxx"

extern HANDLE hEvent; class CHello : public CHelloBase { public: IPFIX(CLSID_CHello); CHello(IUnknown *pUnk); ~CHello(); HRESULT __stdcall PrintSz(LPWSTR pwszString); private: static int cObjRef; };

  1. include "thlo.h"
  2. include "pshlo.h"
  3. include "shlo.hxx"
  4. include "mycls.hxx"

int CHello:cObjRef = 0; CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk) {

   cObjRef++;
   return;

} HRESULT __stdcall CHello::PrintSz(LPWSTR pwszString) {

   printf("%ws\n", pwszString);
   return(ResultFromScode(S_OK));

} CHello::~CHello(void) {

   cObjRef--;
   if( cObjRef == 0 )
       PulseEvent(hEvent);
   return;

}

  1. include "pshlo.h"
  2. include "shlo.hxx"
  3. include "mycls.hxx"

HANDLE hEvent; int _cdecl main(int argc, char * argv[]) {

   ULONG ulRef;
   DWORD dwRegistration;
   CHelloCF *pCF = new CHelloCF();
   hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
   CoInitiali, NULL);
   CoInitializeEx(NULL, COINIT_MULTITHREADED);
   CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER,
       REGCLS_MULTIPLEUSE, &dwRegistration);
   WaitForSingleObject(hEvent, INFINITE);
   CoRevokeClassObject(dwRegistration);
   ulRef = pCF->Release();
   CoUninitialize();
   return(0); 

} extern CLSID CLSID_CHello; extern UUID LIBID_CHelloLib; CLSID CLSID_CHello = { 0x2573F891, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } }; UUID LIBID_CHelloLib = { 0x2573F890, 0xCFEE, 0x101A, { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 } };

  1. include "pshlo.h"
  2. include "shlo.hxx"
  3. include "clsid.h"

int _cdecl main( int argc, char * argv[]) {

   HRESULT hRslt;
   IHello *pHello;
   ULONG ulCnt;
   IMoniker * pmk;
   WCHAR wcsT[_MAX_PATH];
   WCHAR wcsPath[2 * _MAX_PATH];
   wcsPath[0] = '\0';
   wcsT[0] = '\0';
   if( argc 1) {
       mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1);
       wcsupr(wcsPath);
   }
   else {
       fprintf(stderr, "Object path must be specified\n");
       return(1);
   }
   if(argc 2)
       mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1);
   else
       wcscpy(wcsT, L"Hello World");
   printf("Linking to object %ws\n", wcsPath);
   printf("Text String %ws\n", wcsT);
   hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED);
   if(SUCCEEDED(hRslt)) {
       hRslt = CreateFileMoniker(wcsPath, &pmk);
       if(SUCCEEDED(hRslt))
           hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello);
       if(SUCCEEDED(hRslt)) {
           pHello->PrintSz(wcsT);
           Sleep(2000);
           ulCnt = pHello->Release();
       }
       else
           printf("Failure to connect, status: %lx", hRslt);
       CoUninitialize();
   }
   return(0);

} </source>


MSIL

<source> .assembly HelloWorld { }

.method static void Main() {

   .entrypoint
   ldstr "Hello World!"
   call  void [mscorlib]System.Console::WriteLine(string)
   ret

} </source>

GML

На GML: <source> show_message("Hello, World!"); </source> или же <source> draw_text(42, 42, "Hello, World!"); </source> можно и <source> show_error("Hello, World!", false); </source>

Blitz3D, язык для новичков

Способ 1: <source> Text 0,0,"Hello, world!" </source>

Способ 2: <source> Print "Hello, world!" WaitKey ;Или Delay 5000 </source>

Способ 3, с выебонами: <source> Const HWtxt$ = "Hello, world!"

Graphics 800,600,32,2 SetBuffer BackBuffer()

Type TCharacter
 Field c$
End Type

GenerateHelloWorld

While Not KeyDown(1)

Cls
DrawHelloWorld
Flip

Wend

End

Function GenerateHelloWorld()

For i = 1 To Len(HWtxt)
 Local char.TCharacter = New TCharacter
  char\c = Mid(HWtxt,i,1)
Next

End Function

Function DrawHelloWorld()

For char.TCharacter = Each TCharacter
  i = i + 1
 Text i*10,10,char\c
Next

End Function </source>

Универсальный вариант

Универсальный Hello World! на C, C++, Haskell(нихуя, ghc это не ест), Ruby, Python, Perl(x2), HTML, tcl, zsh, make, bash и brainfuck <source>

  1. /* [ <html><head>

<title>I'm a HTML page</title></head><body>

I'm a <marquee><blink>horrible HTML</blink></marquee> page

<script language="Javascript"> </script>~ </source>

NATURAL

<source lang="qbasic"> define data local 1 #BUTTON(A1) end-define Write notitle 'Hello, world!' display notitle 'Hello, world!' print 'Hello, world!' PROCESS GUI ACTION MESSAGE-BOX WITH NULL-HANDLE

 'Hello, world!' ' ' 'IO1'
 #BUTTON
 GIVING *ERROR-nr

Input (ad=od) 'Hello, world!' end </source>

LSL

<source> default {

   state_entry()
   {
     llSay(0,"Hello, world!");
   }

} </source>

Erlang

<source lang="erlang">

  1. !/usr/bin/env escript

main(_Args) ->

       io:format("Hello, World!~n").

</source>

Malbolge

<source> (=<`:9876Z4321UT.-Q+*)M'&%$H"!~}|Bzy?=|{z]KwZY44Eq0/{mlk**hKs_dG5[m_BA{?-Y;;Vb'rR5431M}/.zHGwEDCBA@98\6543W10/.R,+O< </source>

LOLCODE

<source lang="lolcode"> HAI CAN HAS STDIO? VISIBLE "HAI WORLD!" KTHXBYE </source>

Go

<source lang="go"> package main

import "fmt"

func main() { fmt.Println("Hello, world!") } </source>

или проще:

<source lang="go"> package main

func main() { println("Hello, world!") } </source>

ProceRaptor

<source> application ($console,$void);

 var ("st",$string);
 "Hello World!">>st;
 write (st,$line);
 read ($void,$line);

exit(); </source>

Icon

<source> procedure main() write("Hello, world!") end </source>

ABAP

<source lang="abap"> REPORT zhello. WRITE / 'Hello, World!'. </source>

или так <source lang="abap"> REPORT zhello. MESSAGE 'Hello, World!' TYPE 'I'. </source>

или так <source lang="abap"> REPORT zhello.

CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'

 EXPORTING
   titel        = 'Helloworld'
   textline1    = 'Hello'
   textline2    = 'World!'
   start_column = 25
   start_row    = 6.

</source>

Befunge

<source> > # # # # # # # # # 0 v > #,_@#:"Hello, world!" </source> или так <source> 0"!dlroW ,olleH">:#,_@ </source>

TeX

<source lang="latex"> \documentclass[a4paper,12pt]{article} \usepackage[T2A]{fontenc} \usepackage[utf8]{inputenc} \usepackage[english]{babel} \usepackage[pdftex,unicode]{hyperref} \begin{document} Hello, World! \end{document} </source>

(на самом деле предыдущий оратор показал код на LaTeX, а на православном TeX это выглядит куда проще):

<source lang="latex"> Hello, World! </source>

Не совсем так: <source lang="latex"> Hello, World! \bye </source>

Vimscript

<source>

echo 'Hello World!'

</source>

Small Basic

<source> TextWindow.WriteLine("Hello, World!") </source>

Rust

<source> fn main() {

   println!("Hello World!");

} </source>

Swift 2.1

<source lang="c"> print("Hello, world!") //либо так let hello = "Hello World!" print(hello) </source>

MATLAB

<source lang="matlab"> disp('Hello, world!'); </source>

ArnoldC

<source> IT'S SHOWTIME TALK TO THE HAND "hello world" YOU HAVE BEEN TERMINATED </source>

V

<source> _Счетчик Отобразить(_Текст) импорт _ОтобразитьТекст; ->ПриветМир():

   Отобразить "Hello, world!";
   <-0;

. </source>


ЯСОП52

<source>

/*@@ПриветЧел
/* запрет вывода на чек долбанных номеров операций
ВИД_ПЕЧАТИ(Пнс=1);
/* привлечение внимания к оборудованию
ВЫЗОВ(ПП=МерзкаяПищалка,прм1=3);
/* запрос фамилии страдальца
ВВОД_КЛ(ТИПП=С,ТЕКСТ="РУЧНАЯ ОПЕРАЦИЯ 666:ВВЕДИТЕ ФАМИЛИЮ     ОПЕРАТОРА",ИМЯ=фамОпер);
/* вывод на чек и на экран
ВЫВОД(ВД="ПРИВЕТ,",ПОЗ=1,ПЕЧАТЬ=ДА);
ВЫВОД(ВД=фамОпер,ПОЗ=21,ПЕЧАТЬ=ДА);
/* задержка времени 3.6 сек, чтобы оператор успел прочитать на экране сообщение и уронить слезу
ЗАДЕР_В_МС(Т=3600);
ФИНИШ;
/*
/*==========
/* <hate> мерзко пищит,
/* использовать против людей
/*==========
МерзкаяПищалка: НАЧАЛО(прм1=ЦБ2);
/* прм1 - количество повторов звукового сигнала
ПРИСВОИТЬ(ТИПП=ЦБ2,ЗНАЧ=прм1,ИМЯ=ошПерТумбл4);
НЦ(НАЧ=1,КОН=ошПерТумбл4,ШАГ=1,ИНД=И);
 ЗВУК(Пс=ВКЛ);
 ЗАДЕР_В_МС(Т=800);
 ЗВУК(Пс=ОТКЛ);
 ЗАДЕР_В_МС(Т=1200);
КЦ;
КОНЕЦ;
/*==========
/*

</source>