summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--.gitattributes2
-rw-r--r--bash.html.markdown9
-rw-r--r--bg-bg/perl-bg.html.markdown7
-rw-r--r--c++.html.markdown2
-rw-r--r--cobol.html.markdown189
-rw-r--r--crystal.html.markdown4
-rw-r--r--dart.html.markdown2
-rw-r--r--de-de/clojure-macros-de.html.markdown161
-rw-r--r--de-de/elm-de.html.markdown376
-rw-r--r--de-de/perl-de.html.markdown4
-rw-r--r--de-de/pug-de.html.markdown208
-rw-r--r--de-de/ruby-de.html.markdown782
-rw-r--r--el-gr/vim-gr.html.markdown267
-rw-r--r--elixir.html.markdown1
-rw-r--r--es-es/perl-es.html.markdown16
-rw-r--r--es-es/raku-es.html.markdown (renamed from es-es/perl6-es.html.markdown)508
-rw-r--r--fr-fr/perl-fr.html.markdown4
-rw-r--r--git.html.markdown4
-rw-r--r--groovy.html.markdown2
-rw-r--r--it-it/sql-it.html.markdown112
-rw-r--r--it-it/zfs-it.html.markdown361
-rw-r--r--ja-jp/python-jp.html.markdown32
-rw-r--r--jsonnet.html.markdown139
-rw-r--r--ko-kr/vim-kr.html.markdown56
-rw-r--r--ldpl.html.markdown13
-rw-r--r--lua.html.markdown2
-rw-r--r--matlab.html.markdown2
-rw-r--r--mips.html.markdown2
-rw-r--r--moonscript.html.markdown2
-rw-r--r--nix.html.markdown2
-rw-r--r--nl-nl/json-nl.html.markdown13
-rw-r--r--p5.html.markdown2
-rw-r--r--perl.html.markdown4
-rw-r--r--php.html.markdown8
-rw-r--r--pl-pl/perl-pl.html.markdown4
-rw-r--r--powershell.html.markdown34
-rw-r--r--processing.html.markdown10
-rw-r--r--pt-br/perl-pt.html.markdown4
-rw-r--r--python.html.markdown20
-rw-r--r--raku-pod.html.markdown (renamed from perl6-pod.html.markdown)90
-rw-r--r--raku.html.markdown119
-rw-r--r--rst.html.markdown6
-rw-r--r--ru-ru/pascal-ru.html.markdown216
-rw-r--r--ru-ru/perl-ru.html.markdown30
-rw-r--r--ru-ru/ruby-ru.html.markdown2
-rw-r--r--ruby.html.markdown10
-rw-r--r--scala.html.markdown5
-rw-r--r--set-theory.html.markdown162
-rw-r--r--smalltalk.html.markdown2
-rw-r--r--vim.html.markdown2
-rw-r--r--wasm.html.markdown2
-rw-r--r--zh-cn/c-cn.html.markdown2
-rw-r--r--zh-cn/perl-cn.html.markdown4
53 files changed, 3184 insertions, 838 deletions
diff --git a/.gitattributes b/.gitattributes
index 183b7cdb..96d2bb5a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -61,5 +61,5 @@ paren*.html.markdown linguist-language=lisp
pcre*.html.markdown linguist-language=Perl
perl.html.markdown linguist-language=Perl
perl-*.html.markdown linguist-language=Perl
-perl6*.html.markdown linguist-language=Perl6
+raku*.html.markdown linguist-language=Perl6
ruby*.html.markdown linguist-language=Ruby
diff --git a/bash.html.markdown b/bash.html.markdown
index 856db706..59aeaaf4 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -88,6 +88,11 @@ echo ${Variable: -5} # => tring
# String length
echo ${#Variable} # => 11
+# Indirect expansion
+OtherVariable="Variable"
+echo ${!OtherVariable} # => Some String
+# This will expand the value of OtherVariable
+
# Default value for variable
echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
# => DefaultValueIfFooIsMissingOrEmpty
@@ -225,7 +230,9 @@ cat file.txt
# We can also read the file using `cat`:
Contents=$(cat file.txt)
-echo "START OF FILE\n$Contents\nEND OF FILE" # "\n" prints a new line character
+# "\n" prints a new line character
+# "-e" to interpret the newline escape characters as escape characters
+echo -e "START OF FILE\n$Contents\nEND OF FILE"
# => START OF FILE
# => [contents of file.txt]
# => END OF FILE
diff --git a/bg-bg/perl-bg.html.markdown b/bg-bg/perl-bg.html.markdown
index 2ae7a8fd..e6da8965 100644
--- a/bg-bg/perl-bg.html.markdown
+++ b/bg-bg/perl-bg.html.markdown
@@ -11,10 +11,10 @@ translators:
lang: bg-bg
---
-Perl 5 е изключително мощен език за програмиране с широка област на приложение
+Perl е изключително мощен език за програмиране с широка област на приложение
и над 25 годишна история.
-Perl 5 работи на повече от 100 операционни системи от мини до супер-компютри и е
+Perl работи на повече от 100 операционни системи от мини до супер-компютри и е
подходящ както за бърза разработка на скриптове така и за огромни приложения.
```perl
@@ -281,7 +281,7 @@ sub increment {
1;
-# Методите могат да се извикват на клас или на обект като се използва оператора
+# Методите могат да се извикват на клас или на обект като се използва оператора
# стрелка (->).
use MyCounter;
@@ -323,4 +323,3 @@ sub increment {
- [Learn at www.perl.com](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- и идващото с perl: `perldoc perlintro`
-
diff --git a/c++.html.markdown b/c++.html.markdown
index f3dc8e20..59aad210 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -202,7 +202,7 @@ int main()
cout << "Your favorite number is " << myInt << "\n";
// prints "Your favorite number is <myInt>"
- cerr << "Used for error messages";
+ cerr << "Used for error messages";
}
//////////
diff --git a/cobol.html.markdown b/cobol.html.markdown
new file mode 100644
index 00000000..4452bd95
--- /dev/null
+++ b/cobol.html.markdown
@@ -0,0 +1,189 @@
+---
+language: COBOL
+contributors:
+ - ["Hyphz", "http://github.com/hyphz/"]
+filename: learn.COB
+---
+COBOL is a business-oriented language revised multiple times since its original design in 1960. It is claimed to still be used in over 80% of
+organizations.
+
+```cobol
+ *COBOL. Coding like it's 1985.
+ *Compiles with GnuCOBOL in OpenCobolIDE 4.7.6.
+
+ *COBOL has significant differences between legacy (COBOL-85)
+ *and modern (COBOL-2002 and COBOL-2014) versions.
+ *Legacy versions require columns 1-6 to be blank (they are used
+ *to store the index number of the punched card..)
+ *A * in column 7 means a comment.
+ *In legacy COBOL, a comment can only be a full line.
+ *Modern COBOL doesn't require fixed columns and uses *> for
+ *a comment, which can appear in the middle of a line.
+ *Legacy COBOL also imposes a limit on maximum line length.
+ *Keywords have to be in capitals in legacy COBOL,
+ *but are case insensitive in modern.
+
+ *First, we must give our program ID.
+ *Identification division can include other values too,
+ *but they are comments only. Program-id is mandatory.
+ identification division.
+ program-id. learn.
+
+ *Let's declare some variables.
+ data division.
+ working-storage section.
+
+ *Variables are specified by a "picture" - how they should be
+ *displayed, and variable type is inferred from this.
+ *The "01" value is the level number which is used for building
+ *data structures.
+ 01 myname picture xxxxxxxxxx. *> A 10 character string.
+ 01 age picture 999. *> A number up to 3 digits.
+ 01 valx picture 999. *> Another number up to 3 digits.
+ 01 inyear picture s9(7). *> S makes number signed.
+ *> Brackets indicate 7 repeats of 9,
+ *> ie a 6 digit number (not an array).
+
+ *Now let's write some code.
+ procedure division.
+
+ main-procedure.
+ *> COBOL is the language that uses DISPLAY instead of PRINT.
+ *> Note: no full stops after commands. Only after the LAST
+ *> command.
+ display "Hello. What's your name?"
+
+ *> Let's input a string.
+ *> If input too long, later characters are trimmed.
+ accept myname
+ display "Hello " myname *> We can display several things.
+ display "How old are you?"
+
+ *> Let's input a number.
+ *> If input too long, EARLIER characters are trimmed.
+ accept age
+
+ display age *> Left-padded to three chracaters with zeroes,
+ *> because of the defined PICTURE for age.
+
+ *> We have two ways of doing a FOR loop.
+ *> Old style way: doesn't give an index.
+ perform age times
+ display "*" with no advancing *> Ie, no newline at end
+ end-perform
+ display "." *> Output buffer isn't flushed until newline.
+
+ *> New style way: with an index.
+ perform varying valx from 1 by 1 until valx > age
+ display valx "-" with no advancing
+ end-perform
+ display "."
+
+ *> If tests are still good old if tests.
+ if myname = "Bob" then
+ display "I don't like Bob."
+ else
+ display "I don't know you."
+ end-if
+
+ *> There are two ways of doing subprograms and calling
+ *> them.
+ *> The simplest way: a paragraph.
+ perform subparagraph
+
+ *> The complex way, with parameters and stuff.
+ call "eratosthenes" using age returning valx
+
+ display "There were " valx " primes."
+
+ stop run.
+
+ subparagraph. *> Marks the top of an internal subprogram.
+ *> Shares variable score with its caller.
+
+ *> Read year from system timer.
+ *> Remember the whole "year 2000 crisis"? The yyyyddd
+ *> option was added in response to that.
+ accept inyear from day yyyyddd.
+
+ *> We can do math step-by-step like this...
+ divide 1000 into inyear.
+ subtract age from inyear.
+
+ display "You were born in " inyear "."
+
+ *> Or we can just use expressions.
+ compute inyear = 1970 - inyear.
+
+ if inyear >= 0 then
+ display "When you were " inyear ", " with no advancing
+ else
+ display inyear " years before you were born, " with no
+ advancing
+ end-if
+
+ display "COBOL was the most popular language in the world."
+ . *> You can put the final . on a new line if it's clearer.
+
+
+ *If we want to use a subprogram, we use literally a subprogram.
+ *This is the entire program layout, repeated for the
+ *eratosthenes subroutine.
+ identification division.
+ program-id. eratosthenes.
+
+ data division.
+ working-storage section.
+ *Declare an array.
+ *We can declare a variable to use as an index for it at the
+ *same time.
+ 01 sieve pic 9 occurs 999 times indexed by sa, sb.
+ *> Standard cobol doesn't have a boolean type.
+ 01 pstart pic 999.
+ 01 counter pic 999.
+
+ *Our parameters have to be declared in the linkage section.
+ *Their pictures must match the values they're called with.
+ linkage section.
+ 01 maxvalue picture 999.
+
+ *"using" declares our actual parameter variables.
+ *"returning" declares the variable value returned at end.
+ procedure division using maxvalue returning counter.
+ main-procedure.
+
+ display "Here are all the primes up to " maxvalue "."
+
+ perform varying sa from 1 by 1 until sa > maxvalue
+ move 1 to sieve (sa)
+ end-perform
+
+ perform varying sa from 2 by 1 until sa > maxvalue
+ if sieve(sa) = 1 then
+ compute pstart = sa + sa
+ perform varying sb from pstart by sa until sb >
+ maxvalue
+ move 0 to sieve(sb)
+ end-perform
+ end-if
+ end-perform
+
+ initialise counter *> To zero by default for a number.
+
+ perform varying sa from 2 by 1 until sa > maxvalue
+ if sieve(sa) = 1 THEN
+ display sa
+ add 1 to counter
+ end-if
+ end-perform.
+
+ end program eratosthenes.
+
+ end program learn.
+
+```
+
+##Ready For More?
+
+* [GnuCOBOL](https://sourceforge.net/projects/open-cobol/)
+
diff --git a/crystal.html.markdown b/crystal.html.markdown
index 9fae9da3..ae027a8d 100644
--- a/crystal.html.markdown
+++ b/crystal.html.markdown
@@ -229,7 +229,7 @@ b #=> 'b'
c #=> "c"
# Procs represent a function pointer with an optional context (the closure data)
-# It is typically created with a proc litteral
+# It is typically created with a proc literal
proc = ->(x : Int32) { x.to_s }
proc.class # Proc(Int32, String)
# Or using the new method
@@ -551,4 +551,4 @@ ex #=> "ex2"
## Additional resources
-- [Official Documentation](http://crystal-lang.org/)
+- [Official Documentation](https://crystal-lang.org/)
diff --git a/dart.html.markdown b/dart.html.markdown
index 1e7233a4..e94f1203 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -6,7 +6,7 @@ contributors:
- ["Vince Ramces Oliveros", "https://github.com/ram231"]
---
-**Dart** is a single threaded, general puprose programming languages.
+**Dart** is a single threaded, general purpose programming language.
It borrows a lot from other mainstream languages.
It supports Streams, Futures(known as Promises in JavaScript), Generics, First-class functions(closures) and static type checking.
Dart can run in any platform such as Web, CLI, Desktop, Mobile and IoT devices.
diff --git a/de-de/clojure-macros-de.html.markdown b/de-de/clojure-macros-de.html.markdown
new file mode 100644
index 00000000..088a29a8
--- /dev/null
+++ b/de-de/clojure-macros-de.html.markdown
@@ -0,0 +1,161 @@
+---
+language: "clojure macros"
+filename: learnclojuremacros-de.clj
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+translators:
+ - ["Dennis Keller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+Wie mit allen Lisps besitzt auch Clojure die inhärente [Homoikonizität](https://en.wikipedia.org/wiki/Homoiconic),
+die dir den vollen Zugang der Sprache gibt, um
+ Code-Generierungsroutinen zu schreiben. Diese werden "Macros" genannt.
+Macros geben dir eine leistungsarke Möglichkeit, die Sprache
+an deine Bedürfnisse anzupassen.
+
+Sei aber vorsichtig, es wird als schlechter Stil angesehen, wenn du
+ein Macro schreibst, obwohl eine Funktion genausogut funktionieren würde.
+Verwende nur dann ein Macro, wenn du Kontrolle darüber brauchst, wann oder ob Argumente in einer Form evaluiert werden.
+
+Wenn du mit Clojure vertraut sein möchtest, stelle sicher, dass du alles in [Clojure in Y Minutes](/docs/clojure/) verstehst.
+
+```clojure
+;; Definiere ein Macro mit defmacro. Dein Macro sollte eine Liste zurückgeben,
+;; die als Clojure Code evaluiert werden kann.
+;;
+;; Dieses Macro ist das Gleiche, als ob du (reverse "Hallo Welt") geschrieben
+;; hättest
+(defmacro my-first-macro []
+ (list reverse "Hallo Welt"))
+
+;; Inspiziere das Ergebnis eines Macros mit macroexpand oder macroexpand-1.
+;;
+;; Beachte, dass der Aufruf zitiert sein muss.
+(macroexpand '(my-first-macro))
+;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hallo Welt")
+
+;; Du kannst das Ergebnis von macroexpand direkt auswerten.
+(eval (macroexpand '(my-first-macro)))
+; -> (\t \l \e \W \space \o \l \l \a \H)
+
+;; Aber du solltest diese prägnante und funktionsähnliche Syntax verwenden:
+(my-first-macro) ; -> (\t \l \e \W \space \o \l \l \a \H)
+
+;; Du kannst es dir leichter machen, indem du die Zitiersyntax verwendest
+;; um Listen in ihren Makros zu erstellen:
+(defmacro my-first-quoted-macro []
+ '(reverse "Hallo Welt"))
+
+(macroexpand '(my-first-quoted-macro))
+;; -> (reverse "Hallo Welt")
+;; Beachte, dass reverse nicht mehr ein Funktionsobjekt ist, sondern ein Symbol
+
+;; Macros können Argumente haben.
+(defmacro inc2 [arg]
+ (list + 2 arg))
+
+(inc2 2) ; -> 4
+
+;; Aber wenn du versuchst das mit einer zitierten Liste zu machen wirst du
+;; einen Fehler bekommen, weil das Argument auch zitiert sein wird.
+;; Um dies zu umgehen, bietet Clojure einee Art und Weise Macros zu zitieren: `
+;; In ` kannst du ~ verwenden um in den äußeren Bereich zu kommen.
+(defmacro inc2-quoted [arg]
+ `(+ 2 ~arg))
+
+(inc2-quoted 2)
+
+;; Du kannst die normalen destruktuierungs Argumente verwenden. Expandiere
+;; Listenvariablen mit ~@.
+(defmacro unless [arg & body]
+ `(if (not ~arg)
+ (do ~@body))) ; Erinnere dich an das do!
+
+(macroexpand '(unless true (reverse "Hallo Welt")))
+;; ->
+;; (if (clojure.core/not true) (do (reverse "Hallo Welt")))
+
+;; (unless) evaluiert und gibt body zurück, wenn das erste Argument falsch ist.
+;; Andernfalls gibt es nil zurück
+
+(unless true "Hallo") ; -> nil
+(unless false "Hallo") ; -> "Hallo"
+
+;; Die Verwendung Macros ohne Sorgfalt kann viel Böses auslösen, indem es
+;; deine Variablen überschreibt
+(defmacro define-x []
+ '(do
+ (def x 2)
+ (list x)))
+
+(def x 4)
+(define-x) ; -> (2)
+(list x) ; -> (2)
+
+;; Um das zu verhindern kannst du gensym verwenden um einen eindeutigen
+;; Identifikator zu bekommen
+(gensym 'x) ; -> x1281 (oder etwas Ähnliches)
+
+(defmacro define-x-safely []
+ (let [sym (gensym 'x)]
+ `(do
+ (def ~sym 2)
+ (list ~sym))))
+
+(def x 4)
+(define-x-safely) ; -> (2)
+(list x) ; -> (4)
+
+;; Du kannst # innerhalb von ` verwenden um für jedes Symbol automatisch
+;; ein gensym zu erstellen
+(defmacro define-x-hygienically []
+ `(do
+ (def x# 2)
+ (list x#)))
+
+(def x 4)
+(define-x-hygienically) ; -> (2)
+(list x) ; -> (4)
+
+;; Es ist üblich, Hilfsfunktionen mit Macros zu verwenden. Lass uns einige
+;; erstellen, die uns helfen , eine (dumme) arithmetische Syntax
+;; zu unterstützen
+(declare inline-2-helper)
+(defn clean-arg [arg]
+ (if (seq? arg)
+ (inline-2-helper arg)
+ arg))
+
+(defn apply-arg
+ "Bekomme die Argumente [x (+ y)], gebe (+ x y) zurück"
+ [val [op arg]]
+ (list op val (clean-arg arg)))
+
+(defn inline-2-helper
+ [[arg1 & ops-and-args]]
+ (let [ops (partition 2 ops-and-args)]
+ (reduce apply-arg (clean-arg arg1) ops)))
+
+;; Wir können es sofort testen, ohne ein Macro zu erstellen
+(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5))
+
+; Allerdings, brauchen wir ein Macro, wenn wir es zur Kompilierungszeit
+; ausführen wollen
+(defmacro inline-2 [form]
+ (inline-2-helper form))
+
+(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1)))
+; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1)
+
+(inline-2 (1 + (3 / 2) - (1 / 2) + 1))
+; -> 3 (eigentlich, 3N, da die Zahl zu einem rationalen Bruch mit / umgewandelt wird)
+```
+
+### Weiterführende Literatur
+
+[Macros schreiben](http://www.braveclojure.com/writing-macros/)
+
+[Offiziele Docs](http://clojure.org/macros)
+
+[Wann verwendet man Macros?](https://lispcast.com/when-to-use-a-macro/)
diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown
new file mode 100644
index 00000000..08832327
--- /dev/null
+++ b/de-de/elm-de.html.markdown
@@ -0,0 +1,376 @@
+---
+language: Elm
+filename: learnelm.elm
+contributors:
+ - ["Max Goldstein", "http://maxgoldste.in/"]
+translators:
+ - ["waynee95", "https://waynee95.me"]
+lang: de-de
+---
+
+Elm ist eine pure funktionale Programmiersprache. Mit Elm werden GUIs
+(grafische Benutzeroberfläche) für Webanwendungen erstellt. Durch die statische
+Typisierung kann Elm viele Fehler schon bei der Kompilierung abfangen. Ein
+Hauptmerkmal von Elm sind die ausführlichen und gut erklärten Fehlermeldungen.
+
+```haskell
+-- Einzeilige Kommentare beginnen mit 2 Bindestrichen.
+{- So wird ein mehrzeiliger Kommentar angelegt.
+{- Diese können auch verschachtelt werden. -}
+-}
+
+{-- Die Grundlagen --}
+
+-- Arithmetik
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+
+-- Zahlen ohne Punkt sind entweder vom Typ Int oder Float.
+33 / 2 -- 16.5 mit Division von Gleitkommazahlen
+33 // 2 -- 16 mit ganzzahliger Division
+
+-- Exponenten
+5 ^ 2 -- 25
+
+-- Boolsche Werte
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- Strings (Zeichenketten) und Zeichen
+"Das hier ist ein String."
+'a' -- Zeichen
+
+-- Strings können konkateniert werden.
+"Hello " ++ "world!" -- "Hello world!"
+
+{-- Listen und Tupel --}
+
+-- Jedes Element einer Liste muss vom gleichen Typ sein. Listen sind homogen.
+["the", "quick", "brown", "fox"]
+[1, 2, 3, 4, 5]
+-- Das zweite Beispiel kann man auch mit Hilfe der "range" Funktion schreiben.
+List.range 1 5
+
+-- Listen werden genauso wie Strings konkateniert.
+List.range 1 5 ++ List.range 6 10 == List.range 1 10 -- True
+
+-- Mit dem "cons" Operator lässt sich ein Element an den Anfang einer Liste anfügen.
+0 :: List.range 1 5 -- [0, 1, 2, 3, 4, 5]
+
+-- Die Funktionen "head" und "tail" haben als Rückgabewert den "Maybe" Typ.
+-- Dadurch wird die Fehlerbehandlung von fehlenden Elementen explizit, weil
+-- man immer mit jedem möglichen Fall umgehen muss.
+List.head (List.range 1 5) -- Just 1
+List.tail (List.range 1 5) -- Just [2, 3, 4, 5]
+List.head [] -- Nothing
+-- List.funktionsName bedeutet, dass diese Funktion aus dem "List"-Modul stammt.
+
+-- Tupel sind heterogen, jedes Element kann von einem anderen Typ sein.
+-- Jedoch haben Tupel eine feste Länge.
+("elm", 42)
+
+-- Das Zugreifen auf Elemente eines Tupels geschieht mittels den Funktionen
+-- "first" und "second".
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
+
+-- Das leere Tupel, genannt "Unit", wird manchmal als Platzhalter verwendet.
+-- Es ist das einzige Element vom Typ "Unit".
+()
+
+{-- Kontrollfluss --}
+
+-- Eine If-Bedingung hat immer einen Else-Zweig und beide Zweige müssen den
+-- gleichen Typ haben.
+if powerLevel > 9000 then
+ "WHOA!"
+else
+ "meh"
+
+-- If-Bedingungen können verkettet werden.
+if n < 0 then
+ "n is negative"
+else if n > 0 then
+ "n is positive"
+else
+ "n is zero"
+
+-- Mit dem Mustervergleich (pattern matching) kann man bestimmte Fälle direkt
+-- behandeln.
+case aList of
+ [] -> "matches the empty list"
+ [x]-> "matches a list of exactly one item, " ++ toString x
+ x::xs -> "matches a list of at least one item whose head is " ++ toString x
+-- Mustervergleich geht immer von oben nach unten. Würde man [x] als letztes
+-- platzieren, dann würde dieser Fall niemals getroffen werden, weil x:xs diesen
+-- Fall schon mit einschließt (xs ist in dem Fall die leere Liste).
+
+-- Mustervergleich an einem Maybe Typ.
+case List.head aList of
+ Just x -> "The head is " ++ toString x
+ Nothing -> "The list was empty."
+
+{-- Funktionen --}
+
+-- Die Syntax für Funktionen in Elm ist minimal. Hier werden Leerzeichen anstelle
+-- von runden oder geschweiften Klammern verwendet. Außerdem gibt es kein "return"
+-- Keyword.
+
+-- Eine Funktion wird durch ihren Namen, einer Liste von Parametern gefolgt von
+-- einem Gleichheitszeichen und dem Funktionskörper angegeben.
+multiply a b =
+ a * b
+
+-- Beim Aufruf der Funktion (auch Applikation genannt) werden die Argumente ohne
+-- Komma übergeben.
+multiply 7 6 -- 42
+
+-- Partielle Applikation einer Funktion (Aufrufen einer Funktion mit fehlenden
+-- Argumenten). Hierbei entsteht eine neue Funktion, der wir einen Namen geben.
+double =
+ multiply 2
+
+-- Konstanten sind Funktionen ohne Parameter.
+answer =
+ 42
+
+-- Funktionen, die Funktionen als Parameter haben, nennt man Funktionen höherer
+-- Ordnung. In funktionalen Programmiersprachen werden Funktionen als "first-class"
+-- behandelt. Man kann sie als Argument übergeben, als Rückgabewert einer Funktion
+-- zurückgeben oder einer Variable zuweisen.
+List.map double (List.range 1 4) -- [2, 4, 6, 8]
+
+-- Funktionen können auch als anonyme Funktion (Lambda-Funktionen) übergeben werden.
+-- Diese werden mit einem Blackslash eingeleitet, gefolgt von allen Argumenten.
+-- Die Funktion "\a -> a * 2" beschreibt die Funktion f(x) = x * 2.
+List.map (\a -> a * 2) (List.range 1 4) -- [2, 4, 6, 8]
+
+-- Mustervergleich kann auch in der Funktionsdefinition verwendet werden.
+-- In diesem Fall hat die Funktion ein Tupel als Parameter. (Beachte: Hier
+-- werden die Werte des Tupels direkt ausgepackt. Dadurch kann man auf die
+-- Verwendung von "first" und "second" verzichten.)
+area (width, height) =
+ width * height
+
+area (6, 7) -- 42
+
+-- Mustervergleich auf Records macht man mit geschweiften Klammern.
+-- Bezeichner (lokale Variablen) werden mittels dem "let" Keyword angelegt.
+-- (Mehr zu Records weiter unten!)
+volume {width, height, depth} =
+ let
+ area = width * height
+ in
+ area * depth
+
+volume { width = 3, height = 2, depth = 7 } -- 42
+
+-- Rekursive Funktion
+fib n =
+ if n < 2 then
+ 1
+ else
+ fib (n - 1) + fib (n - 2)
+
+List.map fib (List.range 0 8) -- [1, 1, 2, 3, 5, 8, 13, 21, 34]
+
+-- Noch eine rekursive Funktion (Nur ein Beispiel, verwende stattdessen immer
+-- List.length!)
+listLength aList =
+ case aList of
+ [] -> 0
+ x::xs -> 1 + listLength xs
+
+-- Funktionsapplikation hat die höchste Präzedenz, sie binden stärker als Operatoren.
+-- Klammern bietet die Möglichkeit der Bevorrangung.
+cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1
+-- Als erstes wird die Funktion "degrees" mit dem Wert 30 aufgerufen.
+-- Danach wird das Ergenis davon den Funktionen "cos", bzw. "sin" übergeben.
+-- Dann wird das Ergebnis davon mit 2 quadriert und als letztes werden diese
+-- beiden Werte dann addiert.
+
+{-- Typen und Typ Annotationen --}
+
+-- Durch Typinferenz kann der Compiler jeden Typ genau bestimmen. Man kann diese
+-- aber auch manuell selber angeben (guter Stil!).
+-- Typen beginnen immer mit eine Großbuchstaben. Dabei liest man "x : Typ" als
+-- "x" ist vom Typ "Typ".
+-- Hier ein paar übliche Typen:
+5 : Int
+6.7 : Float
+"hello" : String
+True : Bool
+
+-- Funktionen haben ebenfalls einen Typ. Dabei ist der ganz rechte Typ der
+-- Rückgabetyp der Funktion und alle anderen sind die Typen der Parameter.
+not : Bool -> Bool
+round : Float -> Int
+
+-- Es ist guter Stil immer den Typ anzugeben, da diese eine Form von Dokumentation
+-- sind. Außerdem kann so der Compiler genauere Fehlermeldungen geben.
+double : Int -> Int
+double x = x * 2
+
+-- Funktionen als Parameter werden durch Klammern angegeben. Die folgende Funktion
+-- ist nicht auf einen Typ festgelegt, sondern enthält Typvariablen (beginnend
+-- mit Kleinbuchstaben). Die konkreten Typen werden erst bei Anwendung der
+-- Funktion festgelegt. "List a" bedeutet, dass es sich um eine Liste mit
+-- Elementen vom Typ "a" handelt.
+List.map : (a -> b) -> List a -> List b
+
+-- Es gibt drei spezielle kleingeschriebene Typen: "number", "comparable" und
+-- "appendable".
+add : number -> number -> number
+add x y = x + y -- funktioniert mit Ints und Floats.
+
+max :: comparable -> comparable -> comparable
+max a b = if a > b then a else b -- funktioniert mit Typen, die vergleichbar sind.
+
+append :: appendable -> appendable -> appendable
+append xs ys = xs ++ ys -- funktioniert mit Typen, die konkatenierbar sind.
+
+append "hello" "world" -- "helloworld"
+append [1,1,2] [3,5,8] -- [1,1,2,3,5,8]
+
+{-- Eigene Datentypen erstellen --}
+
+-- Ein "Record" ist ähnlich wie ein Tupel, nur das jedes Feld einen Namne hat.
+-- Dabei spielt die Reihenfolge keine Rolle.
+{ x = 3, y = 7 }
+
+-- Um auf Werte eines Records zuzugreifen, benutzt man einen Punkt gefolgt
+-- von dem Namen des Feldes.
+{ x = 3, y = 7 }.x -- 3
+
+-- Oder mit einer Zugriffsfunktion, welche aus einem Punkt und dem Feldnamen besteht.
+.y { x = 3, y = 7 } -- 7
+
+-- Wert eines Feldes ändern. (Achtung: Das Feld muss aber vorher schon vorhanden sein!)
+{ person |
+ name = "George" }
+
+-- Mehrere Felder aufeinmal ändern unter Verwendung des alten Wertes.
+{ particle |
+ position = particle.position + particle.velocity,
+ velocity = particle.velocity + particle.acceleration }
+
+-- Du kannst ein Record auch als Typ Annotation verwenden.
+-- (Beachte: Ein Record Typ benutzt einen Doppelpunkt und ein Record Wert benutzt
+-- ein Gleichheitszeichen!)
+origin : { x : Float, y : Float, z : Float }
+origin =
+ { x = 0, y = 0, z = 0 }
+
+-- Durch das "type" Keyword kann man einem existierenden Typen einen Namen geben.
+type alias Point3D =
+ { x : Float, y : Float, z : Float }
+
+-- Der Name kann dann als Konstruktor verwendet werden.
+otherOrigin : Point3D
+otherOrigin =
+ Point3D 0 0 0
+
+-- Aber es ist immernoch der selbe Typ, da es nur ein Alias ist!
+origin == otherOrigin -- True
+
+-- Neben den Records gibt es auch noch so genannte Summentypen.
+-- Ein Summentyp hat mehrere Konstruktoren.
+type Direction =
+ North | South | East | West
+
+-- Ein Konstruktor kann außerdem noch andere Typen enthalten. Rekursion ist
+-- auch möglich.
+type IntTree =
+ Leaf | Node Int IntTree IntTree
+
+-- Diese können auch als Typ Annotation verwendet werden.
+root : IntTree
+root =
+ Node 7 Leaf Leaf
+
+-- Außerdem können auch Typvariablen verwendet werden in einem Konstruktor.
+type Tree a =
+ Leaf | Node a (Tree a) (Tree a)
+
+-- Beim Mustervergleich kann man auf die verschiedenen Konstruktoren matchen.
+leftmostElement : Tree a -> Maybe a
+leftmostElement tree =
+ case tree of
+ Leaf -> Nothing
+ Node x Leaf _ -> Just x
+ Node _ subtree _ -> leftmostElement subtree
+
+{-- Module und Imports --}
+
+-- Die Kernbibliotheken und andere Bibliotheken sind in Module aufgeteilt.
+-- Für große Projekte können auch eigene Module erstellt werden.
+
+-- Eine Modul beginnt mit ganz oben. Ohne diese Angabe befindet man sich
+-- automatisch im Modul "Main".
+module Name where
+
+-- Ohne genaue Angabe von Exports wird alles exportiert. Es können aber alle
+-- Exporte explizit angegeben werden.
+module Name (MyType, myValue) where
+
+-- Importiert das Modul "Dict". Jetzt kann man Funktionen mittels "Dict.insert"
+-- aufrufen.
+import Dict
+
+-- Importiert das "Dict" Modul und den "Dict" Typ. Dadurch muss man nicht "Dict.Dict"
+-- verwenden. Man kann trotzdem noch Funktionen des Moduls aufrufen, wie "Dict.insert".
+import Dict exposing (Dict)
+
+-- Abkürzung für den Modulnamen. Aufrufen der Funktionen mittels "C.funktionsName".
+import Graphics.Collage as C
+
+{-- Kommandozeilen Programme --}
+
+-- Eine Elm-Datei kompilieren.
+$ elm make MyFile.elm
+
+-- Beim ersten Aufruf wird Elm die "core" Bibliotheken installieren und eine
+-- "elm-package.json"-Datei anlegen, die alle Informationen des Projektes
+-- speichert.
+
+-- Der Reactor ist ein Server, welche alle Dateinen kompiliert und ausführt.
+$ elm reactor
+
+-- Starte das REPL (read-eval-print-loop).
+$ elm repl
+
+-- Bibliotheken werden durch den Github-Nutzernamen und ein Repository identifiziert.
+-- Installieren einer neuen Bibliothek.
+$ elm package install elm-lang/html
+-- Diese wird der elm-package.json Datei hinzugefügt.
+
+-- Zeigt alle Veränderungen zwischen zwei bestimmten Versionen an.
+$ elm package diff elm-lang/html 1.1.0 2.0.0
+-- Der Paketmanager von Elm erzwingt "semantic versioning"!
+```
+
+Elm ist eine besonders kleine Programmiersprache. Jetzt hast du genug Wissen an
+deiner Seite, um dich in fast jedem Elm Code zurecht zu finden.
+
+Noch ein paar weitere hilfreiche Ressourcen (in Englisch):
+
+- Die [Elm Homepage](http://elm-lang.org/). Dort findest du:
+
+ - [Anleitung zur Installierung von Elm](http://elm-lang.org/install)
+ - [Dokumentation](http://elm-lang.org/docs), sowie eine [Referenz zur Syntax](http://elm-lang.org/docs/syntax)
+ - Viele hilfreiche [Beispiele](http://elm-lang.org/examples)
+
+- Dokumentation der [Elm Kernbibliotheken](http://package.elm-lang.org/packages/elm-lang/core/latest/). Insbesondere:
+
+ - [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics) (standardmäßig importiert)
+ - [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) sowie [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) (benutzt für Fehlerbehandlung)
+ - Datenstrukturen, wie [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), und [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set)
+ - JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) und [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode)
+
+- [Die Elm Architektur](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture).
+
+- Die [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss).
diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown
index fd8fb3c4..13c00b01 100644
--- a/de-de/perl-de.html.markdown
+++ b/de-de/perl-de.html.markdown
@@ -8,9 +8,9 @@ translators:
lang: de-de
---
-Perl 5 ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte.
+Perl ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte.
-Perl 5 läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl 5 ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte.
+Perl läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte.
```perl
# Einzeilige Kommentare beginnen mit dem # Symbol.
diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown
new file mode 100644
index 00000000..c86494ce
--- /dev/null
+++ b/de-de/pug-de.html.markdown
@@ -0,0 +1,208 @@
+---
+language: Pug
+contributors:
+ - ["Michael Warner", "https://github.com/MichaelJGW"]
+filename: lernepug-de.pug
+translators:
+ - ["denniskeller", "https://github.com/denniskeller"]
+lang: de-de
+---
+
+## Erste Schritte mit Pug
+
+Pug ist eine kleine Sprache, die zu HTML kompiliert. Sie hat eine
+saubere Syntax mit zusätzlichen Funktionen wie if Anweisungen und Schleifen.
+Sie kann auch als serverseitige Templatingsprache für Serversprachen
+wie NodeJS verwendet werden.
+
+### Die Sprache
+```pug
+
+//- Einzeilenkommentar
+
+//- Mehrzeiliger
+ Kommentar
+
+//- ---TAGS---
+//- Grundlagen
+div
+//- <div></div>
+h1
+//- <h1></h1>
+mein-benutzerdefiniertesTag
+//- <mein-benutzerdefiniertesTag></mein-benutzerdefiniertesTag>
+
+//- Geschwister
+div
+div
+//- <div></div>
+ <div></div>
+
+//- Kind
+div
+ div
+//- <div>
+ <div></div>
+ </div>
+
+//- Text
+h1 Hallo Welt
+//- <h1>Hallo Welt</h1>
+
+//- Multizeilentext
+div.
+ Hallo
+ Welt
+//- <div>
+ Hallo
+ Welt
+ </div>
+
+//- ---ATTRIBUTE---
+div(class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled)
+//- <div class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled></div>
+
+//- Kurzhand
+span.meine-klasse
+//- <span class="meine-klasse"></span>
+.meine-klasse
+//- <div class="meine-klasse"></div>
+div#meine-id
+//- <div id="meine-id"></div>
+div#meine-id.meine-klasse
+//- <div class="meine-klasse" id="meine-id"></div>
+
+
+//- ---JS---
+- const sprache = "pug";
+
+//- Multizeilen JS
+-
+ const srache = "pug";
+ const cool = true;
+
+//- JS Klassen
+- const meineKlasse = ['class1', 'class2', 'class3']
+div(class=meineKlasse)
+//- <div class="class1 class2 class3"></div>
+
+//- JS Stil
+- const meineStile = {'color':'white', 'background-color':'blue'}
+div(styles=meineStile)
+//- <div styles="{&quot;color&quot;:&quot;white&quot;,&quot;background-color&quot;:&quot;blue&quot;}"></div>
+
+//- JS Attributte
+- const meineAttribute = {"src": "foto.png", "alt": "meine Bilder"}
+img&attributes(meineAttribute)
+//- <img src="foto.png" alt="meine Bilder">
+- let deaktiviert = false
+input(type="text" disabled=deaktiviert)
+//- <input type="text">
+- deaktiviert = true
+input(type="text" disabled=deaktiviert)
+//- <input type="text" disabled>
+
+//- JS Templating
+- const name = "Bob";
+h1 Hi #{name}
+h1= name
+//- <h1>Hi Bob</h1>
+//- <h1>Bob</h1>
+
+//- ---Schleifen---
+
+//- 'each' und 'for' machen das Selbe. Wir werden nur 'each' verwenden.
+
+each value, i in [1,2,3]
+ p=value
+//-
+ <p>1</p>
+ <p>2</p>
+ <p>3</p>
+
+each value, index in [1,2,3]
+ p=value + '-' + index
+//-
+ <p>1-0</p>
+ <p>2-1</p>
+ <p>3-2</p>
+
+each value in []
+ p=value
+//-
+
+each value in []
+ p=value
+else
+ p Keine Werte sind hier
+
+//- <p>Keine Werte sind hier</p>
+
+//- ---BEDINGUNGEN---
+
+- const zahl = 5
+if zahl < 5
+ p zahl ist kleiner als 5
+else if zahl > 5
+ p zahl ist größer als 5
+else
+ p zahl ist 5
+//- <p>zahl ist 5</p>
+
+- const bestellungsStatus = "Ausstehend";
+case bestellungsStatus
+ when "Ausstehend"
+ p.warn Deine Bestellung steht noch aus
+ when "Abgeschlossen"
+ p.success Bestellung ist abgeschlossen.
+ when -1
+ p.error Ein Fehler ist aufgetreten
+ default
+ p kein Bestellprotokoll gefunden
+//- <p class="warn">Deine Bestellung steht noch aus</p>
+
+//- --INCLUDE--
+//- File path -> "includes/nav.png"
+h1 Firmenname
+nav
+ a(href="index.html") Home
+ a(href="about.html") Über uns
+
+//- Dateipfad -> "index.png"
+html
+ body
+ include includes/nav.pug
+//-
+ <html>
+ <body>
+ <h1>Firmenname</h1>
+ <nav><a href="index.html">Home</a><a href="about.html">Über uns</a></nav>
+ </body>
+ </html>
+
+//- Importiere JS und CSS
+script
+ include scripts/index.js
+style
+ include styles/theme.css
+
+//- ---MIXIN---
+mixin basic()
+ div Hallo
++basic("Bob")
+//- <div>Hallo</div>
+
+mixin comment(name, kommentar)
+ div
+ span.comment-name= name
+ div.comment-text= kommentar
++comment("Bob", "Das ist super")
+//- <div>Hallo</div>
+
+```
+
+
+### Zusätzliche Ressourcen
+- [The Site](https://pugjs.org/)
+- [The Docs](https://pugjs.org/api/getting-started.html)
+- [Github Repo](https://github.com/pugjs/pug)
diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown
index e14603cd..8025a8c0 100644
--- a/de-de/ruby-de.html.markdown
+++ b/de-de/ruby-de.html.markdown
@@ -1,5 +1,6 @@
---
language: ruby
+filename: ruby-de.rb
contributors:
- ["David Underwood", "http://theflyingdeveloper.com"]
- ["Joel Walden", "http://joelwalden.net"]
@@ -11,602 +12,677 @@ contributors:
- ["Dzianis Dashkevich", "https://github.com/dskecse"]
- ["Levi Bostian", "https://github.com/levibostian"]
- ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gabriel Halley", "https://github.com/ghalley"]
+ - ["Persa Zula", "http://persazula.com"]
+ - ["Jake Faris", "https://github.com/farisj"]
+ - ["Corey Ward", "https://github.com/coreyward"]
+ - ["Jannik Siebert", "https://github.com/janniks"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
translators:
- ["Christian Albrecht", "https://github.com/coastalchief"]
- ["Dennis Keller", "https://github.com/denniskeller"]
-filename: ruby-de.rb
+ - ["Paul Götze", "https://gitub.com/paulgoetze"]
lang: de-de
---
-# Dies ist ein Kommentar
+```ruby
+# Das ist ein Kommentar
=begin
-Dies sind multi-line
-Kommentare. Niemand benutzt
-die wirklich.
+Das ist ein mehrzeiliger Kommentar.
+Die Anfangszeile muss mit "=begin" beginnen
+und die Endzeile muss mit "=end" beginnen.
+
+Alternativ kannst du jede Zeile in einem
+mehrzeiligen Kommentar mit dem # Zeichen beginnen.
=end
-# Objekte - Alles ist ein Objekt
+# In Ruby ist (fast) alles ein Objekt.
+# Das schließt Zahlen ein...
+3.class #=> Integer
-## Zahlen sind Objekte
-```
-3.class #=> Fixnum
-3.to_s #=> "3"
-```
+# ...und Zeichenketten (Strings)...
+"Hallo".class #=> String
-### Simple Arithmetik
-```
+# ...und sogar Methoden!
+"Hallo".method(:class).class #=> Method
+
+# Simple Arithmetik
1 + 1 #=> 2
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
-2**5 #=> 32
-```
+2 ** 5 #=> 32
+5 % 3 #=> 2
-// Arithmetik ist aber eigentlich nur syntaktischer Zucker
-// um eine Methode eines Objekt aufzurufen
-```
+# Bitweise Operatoren
+3 & 5 #=> 1
+3 | 5 #=> 7
+3 ^ 5 #=> 6
+
+# Arithmetik ist aber eigentlich nur syntaktischer Zucker
+# um eine Methode eines Objekts aufzurufen
1.+(3) #=> 4
10.* 5 #=> 50
-```
+100.methods.include?(:/) #=> true
-## Special values sind Objekte
-```
-nil # Nothing to see here
-true # truth
-false # falsehood
+## Spezielle Werte sind Objekte
+nil # Equivalent zu null in anderen Sprachen
+true # Wahrheitswert
+false # Falschheitswert
nil.class #=> NilClass
true.class #=> TrueClass
false.class #=> FalseClass
-```
-## Objektvergleiche
-### Gleicheit
-```
+# Gleicheit
1 == 1 #=> true
2 == 1 #=> false
-```
-### Ungleichheit
-```
+
+# Ungleichheit
1 != 1 #=> false
2 != 1 #=> true
-```
-### Neben false selbst, nil ist ein anderer 'falsey' Wert
-```
-!nil #=> true
-!false #=> true
-!0 #=> false
-```
-### Weitere Vergleiche
-```
+
+# Neben false selbst, ist nil der einzige andere
+# zu Falsch evaluierende Wert
+
+!!nil #=> false
+!!false #=> false
+!!0 #=> true
+!!"" #=> true
+
+# Weitere Vergleiche
1 < 10 #=> true
1 > 10 #=> false
2 <= 2 #=> true
2 >= 2 #=> true
-```
+
+# Kombinierter Vergleichsoperator (gibt `1` zurück wenn das erste Argument
+# größer ist, und `-1`, wenn das zweite Argument größer ist, sonst `0`)
+1 <=> 10 #=> -1 (1 < 10)
+10 <=> 1 #=> 1 (10 > 1)
+1 <=> 1 #=> 0 (1 == 1)
+
### Logische Operatoren
-```
true && false #=> false
true || false #=> true
-!true #=> false
-```
-Es gibt alternative Versionen der logischen Operatoren mit niedrigerer
-Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um
-verschiedenen Ausdrücke zu verketten bis einer true oder false zurück
-liefert.
+# Es gibt alternative Versionen der logischen Operatoren mit niedrigerer
+# Wertigkeit. Diese werden meistens zur Flusskontrolle eingesetzt, um
+# verschiedenen Ausdrücke zu verketten bis einer true oder false zurück
+# liefert.
-#### and
-##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist.
+# `do_something_else` wird nur ausgewertet wenn `do_something` true ist.
do_something() and do_something_else()
-
-#### or
-#####`log_error` wird nur ausgewertet wenn `do_something` false ist.
+# `log_error` wird nur ausgewertet wenn `do_something` false ist.
do_something() or log_error()
-## Strings sind Objekte
-```
-'I am a string'.class #=> String
-"I am a string too".class #=> String
+# String Interpolation
+placeholder = 'Ruby'
+"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungszeichen füllen."
+#=> "Ich kann in Ruby Platzhalter mit doppelten Anführungszeichen füllen."
-platzhalter = 'Ruby'
-"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen."
-```
-Einfache Anführungszeichen sollten bevorzugt werden.
-Doppelte Anführungszeichen führen interne Berechnungen durch.
+# Du kannst Strings mit `+` verbinden, nicht jedoch mit anderen Typen
+'hallo ' + 'Welt' #=> "hallo Welt"
+'Hallo ' + 3 #=> TypeError: no implicit conversion of Integer into String
+'hallo ' + 3.to_s #=> "hallo 3"
+"hallo #{3}" #=> "hallo 3"
+
+# ...oder Strings mit Operatoren kombinieren
+'hallo ' * 3 #=> "hallo hallo hallo "
+
+# ...oder Strings an andere Strings anhängen
+'hallo' << ' Welt' #=> "hallo Welt"
+
+# Du kannst Text mit einer neuen Zeile am Ende ausgeben
+puts "Ich gebe Text aus!"
+#=> Ich gebe Text aus!
+#=> nil
+
+# ...oder Text ohne einen Zeilenumbruch ausgeben
+print "Ich gebe Text aus!"
+#=> "Ich gebe Text aus!" => nil
-### Strings können verbunden werden, aber nicht mit Zahlen
-```
-'hello ' + 'world' #=> "hello world"
-'hello ' + 3 #=> TypeError: can't convert Fixnum into String
-```
-#### Zahl muss in String konvertiert werden
-```
-'hello ' + 3.to_s #=> "hello 3"
-```
-### Text ausgeben
-```
-puts "I'm printing!"
-```
# Variablen
-## Zuweisungen
-### Diese Zuweisung gibt den zugeordneten Wert zurück
-```
x = 25 #=> 25
x #=> 25
-```
-### Damit funktionieren auch mehrfache Zuweisungen
-```
+
+# Beachte, dass Zuweisungen den zugewiesenen Wert zurückgeben.
+# D.h. du kannst mehrfache Zuweisungen machen.
+
x = y = 10 #=> 10
x #=> 10
y #=> 10
-```
-## Benennung
-### Konvention ist snake_case
-```
+
+# Nutze snake_case für Variablennamen.
snake_case = true
-```
-### Benutze verständliche Variablennamen
-```
-path_to_project_root = '/good/name/'
-path = '/bad/name/'
-```
-# Symbols (sind auch Objekte)
-Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern
-als integer repräsentiert werden. Sie werden häufig anstelle von Strings
-verwendet, um sinnvoll Werte zu übermitteln.
-Symbols werden mit dem Doppelpunkt gekennzeichnet.
-```
+# Nutze verständliche Variablennamen.
+path_to_project_root = '/guter/Name/'
+m = '/schlechter/Name/'
+
+
+# Symbole sind unveränderliche, wiederverwendbare Konstanten, welche intern
+# als Integer repräsentiert werden. Sie werden häufig anstelle von Strings
+# verwendet, um semantisch sinnvoll Werte zu übermitteln.
+# Symbols werden mit dem Doppelpunkt gekennzeichnet.
+
:pending.class #=> Symbol
+
status = :pending
+
status == :pending #=> true
+
status == 'pending' #=> false
+
status == :approved #=> false
-```
+
+# Strings können in Symbole konvertiert werden und umgekehrt.
+status.to_s #=> "pending"
+"argon".to_sym #=> :argon
+
# Arrays
-## Ein Array anlegen
-```
+# Das ist ein Array.
array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
-```
-## Array können verschiedene Typen beinhalten
-```
+# Array können verschiedene Typen beinhalten
[1, 'hello', false] #=> [1, "hello", false]
-```
-## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf
-## [0] eigentlich die Methode [] des Array Objekts aufgerufen.
-```
-array.[] 0 #=> 1
-array.[] 12 #=> nil
-```
+## Arrays könnenindiziert werden.
-## Arrays können von vorne indiziert werden
-```
+# Von vorne...
array[0] #=> 1
+array.first #=> 1
array[12] #=> nil
-```
-## Arrays können von hinten indiziert werden
-```
+# ...oder von hinten...
array[-1] #=> 5
-```
+array.last #=> 5
-## Arrays können mit Start Index und Länge indiziert werden
-```
+# ...oder mit einem Startindex und einer Länge...
array[2, 3] #=> [3, 4, 5]
-```
-## Arrays können mit einer Range indiziert werden
-```
+# ...oder mit einem Range...
array[1..3] #=> [2, 3, 4]
-```
-## Einen Wert hinzufügen
-```
+# Du kanns ein Array umkehren.
+# Gib ein neues Array mit umgkehrten Werten zurück
+[1,2,3].reverse #=> [3,2,1]
+
+# Kehre ein Array an Ort und Stelle um, um die Variable mit den
+# umgekehrten Werten zu aktualisieren.
+a = [1,2,3]
+a.reverse! #=> a==[3,2,1] wegen des Aufrufs von reverse mit Ausrufezeichens ('!')
+
+# Wie bei der Arithmetik, ist Zugriff mit [index] nur
+# syntaktischer Zucker für den Aufruf der `[]` Methode auf dem Objekt.
+array.[] 0 #=> 1
+array.[] 12 #=> nil
+
+# Du kannst Werte zu einem Array hinzufügen...
array << 6 #=> [1, 2, 3, 4, 5, 6]
+# Oder so
array.push(6) #=> [1, 2, 3, 4, 5, 6]
-```
-## Testen, ob ein Element schon vorhanden ist
-```
+# ...und testen ob ein Element schon vorhanden ist
array.include?(1) #=> true
-```
-# Hashes
-Hashes sind das Hauptfeature um Key/Values zu speichern
+# Hashes sind Rubys Hauptdatenstruktur for Schlüssel/Wert Paare.
+# Hashes werden durch geschweifte Klammern gekennzeichnet.
+hash = { 'Farbe' => 'grün', 'Nummer' => 5 }
-## Ein Hash anlegen
-```
-hash = { 'color' => 'green', 'number' => 5 }
-hash.keys #=> ['color', 'number']
-```
+hash.keys #=> ['farbe', 'nummer']
-## Wert per key herausfinden
-```
-hash['color'] #=> 'green'
-hash['number'] #=> 5
-hash['nothing here'] #=> nil
-// Fragen an einen Hash nach einem Schlüssel, der nicht existiert, ruft nil hervor:
-```
+# Hashes can be quickly looked up by key.
+hash['Farbe'] #=> "grün"
+hash['Nummer'] #=> 5
-## Symbols können auch keys sein
-```
-new_hash = { defcon: 3, action: true }
-new_hash.keys #=> [:defcon, :action]
-```
+# Abfragen eines nicht vorhandenen Schlüssels, gibt nil zurück.
+hash['nicht vorhanden'] #=> nil
-## Testen ob ein Key oder ein Value existiert
-```
-new_hash.has_key?(:defcon) #=> true
-new_hash.has_value?(3) #=> true
-```
+# Wenn du Symbole als Schlüssel in einem Hash verwendest, kannst du
+# eine alternative Syntax verwenden.
+hash = { :defcon => 3, :action => true }
+hash.keys #=> [:defcon, :action]
-### Tipp: Arrays und Hashes sind Enumerable
-### Und haben gemeinsame, hilfreiche Methoden wie:
-### each, map, count, and more
+hash = { defcon: 3, action: true }
+hash.keys #=> [:defcon, :action]
+
+# Testen ob ein Schlüssel oder Wert im Hash existiert
+hash.key?(:defcon) #=> true
+hash.value?(3) #=> true
+
+# Tipp: Arrays und Hashes sind Enumerables!
+# Sie haben viele nützliche Methoden gemein, wie each, map, count, und andere.
# Kontrolstrukturen
-## if
-```
+
+# Bedingungen
if true
- 'if statement'
+ 'wenn Bedingung'
elsif false
- 'else if, optional'
+ 'sonst wenn, optional'
else
- 'else, also optional'
+ 'sonst, auch optional'
end
-```
-## for - Allerdings werden for Schleifen nicht oft vewendet.
-```
-for counter in 1..5
- puts "iteration #{counter}"
-end
-```
-## Stattdessen: "each" Methode und einen Bloch übergeben
-Ein Block ist ein Codeteil, den man einer Methode übergeben kann
-Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen
-Programmiersprachen.
-```
+# Wenn eine Kontrollstruktur keinen Code-Block, sondern einen einzigen
+# Ausdruck ausführt, dann kannst du die nachgestellte if-Notation verwenden
+warnings = ['Nachname fehlt', 'Adresse zu kurz']
+puts("Vorhandene Warnungen:\n" + warnings.join("\n")) if !warnings.empty?
+
+# Formuliere die Bedingung um, wenn sich `unless` besser liest als `if`
+puts("Vorhandene Warnungen:\n" + warnings.join("\n")) unless warnings.empty?
+
+# Schleifen
+# Traditionell ist das Benutzen von `for` Schleifen in Ruby eher unüblich.
+# Stattdessen werden diese mit Hilfe von Enumerables implementiert, was mit
+# dem Aufrufen von `each` einhergeht.
(1..5).each do |counter|
- puts "iteration #{counter}"
+ puts "Iteration #{counter}"
+end
+
+# Was in etwa das selbe ist wie Folgendes (selten in Ruby zu sehen).
+for counter in 1..5
+ puts "Iteration #{counter}"
end
-```
-Die each Methode einer Range führt den Block für jedes Element der Range aus.
+# Das `do |variable| ... end` Konstrukt wird `block` genannt.
+# Blocks sind vergleichbar mit Lambdas, anonymen Funktionen
+# oder Closures in anderen Programmiersprachen.
+# Sie können als Objekte übergeben, aufgerufen oder als Methoden
+# zugewiesen werden.
-Dem Block wird ein "counter" parameter übergeben.
+# Die `each` Methode eines Ranges führt den Block einmal für jedes
+# Element des Ranges aus.
+# Dem Block wird eine counter Variable als Parameter übergeben.
-### Den Block kann man auch in geschweiften Klammern schreiben
-```
-(1..5).each { |counter| puts "iteration #{counter}" }
-```
+# Du kannst einen Block auch mit geschweiften Klammern schreiben.
+(1..5).each { |counter| puts "Iteration #{counter}" }
-### Each kann auch über den Inhalt von Datenstrukturen iterieren
-```
+# Each kann auch über den Inhalt von Datenstrukturen iterieren.
array.each do |element|
- puts "#{element} is part of the array"
+ puts "#{element} is Teil des Arrays"
end
+
hash.each do |key, value|
- puts "#{key} is #{value}"
+ puts "#{key} ist #{value}"
+end
+
+# Um auf den Laufindex zuzugreifen kannst du `each_with_index` verwenden
+# und eine index Variable definieren.
+array.each_with_index do |element, index|
+ puts "#{element} ist Nummer #{index} im Array"
end
counter = 1
while counter <= 5 do
- puts "iteration #{counter}"
+ puts "Iteration #{counter}"
counter += 1
end
-```
+#=> Iteration 1
+#=> Iteration 2
+#=> Iteration 3
+#=> Iteration 4
+#=> Iteration 5
+
+# Es gibt einige andere hilfreiche Schleifenfunktionen in Ruby.
+# Wie etwa 'map', 'reduce', 'inject' und viele andere mehr.
+# Map zum Beispiel iteriert über das Array, führt für jedes Element
+# die Anweisungen aus,
+# die im Block definiert sind und gibt ein völlig neues Array zurück.
+array = [1,2,3,4,5]
+doubled = array.map do |element|
+ element * 2
+end
+puts doubled
+#=> [2,4,6,8,10]
+puts array
+#=> [1,2,3,4,5]
-## case
-```
+# Case Konstruct
grade = 'B'
case grade
when 'A'
- puts 'Way to go kiddo'
+ puts 'So wird’s gemacht'
when 'B'
- puts 'Better luck next time'
+ puts 'Viel Glück beim nächsten Mal'
when 'C'
- puts 'You can do better'
+ puts 'Das kannst du besser'
when 'D'
- puts 'Scraping through'
+ puts 'Gerade so durch'
when 'F'
- puts 'You failed!'
+ puts 'Durchgefallen!'
else
- puts 'Alternative grading system, eh?'
+ puts 'Anderes Bewertungssystem, was?'
end
-=> "Better luck next time"
-```
+#=> "Viel Glück beim nächsten Mal"
-### Case können auch ranges
-```
+# Case kann auch Ranges benutzen
grade = 82
case grade
when 90..100
- puts 'Hooray!'
+ puts 'Hurra!'
when 80...90
- puts 'OK job'
+ puts 'OK gemacht'
else
- puts 'You failed!'
+ puts 'Durchgefallen!'
end
-=> "OK job"
-```
+#=> "OK gemacht"
-# Exception handling:
-```
+# Fehlerbehandlung
begin
- # code here that might raise an exception
- raise NoMemoryError, 'You ran out of memory.'
+ # Code der einen Fehler wirft...
+ raise NoMemoryError, 'Dein Speicher ist voll.'
rescue NoMemoryError => exception_variable
- puts 'NoMemoryError was raised', exception_variable
+ puts 'NoMemoryError ist aufgetreten', exception_variable
rescue RuntimeError => other_exception_variable
- puts 'RuntimeError was raised now'
+ puts 'RuntimeError ist aufgetreten'
else
- puts 'This runs if no exceptions were thrown at all'
+ puts 'Das wird ausgeführt, wenn keine Fehler geworfen wurden'
ensure
- puts 'This code always runs no matter what'
+ puts 'Dieser Code wird immer ausgeführt, egal was vorher passiert'
end
-```
-# Funktionen
-```
+
+# Methoden
+
def double(x)
x * 2
end
-```
-## Funktionen (und Blocks)
-## geben implizit den Wert des letzten Statements zurück
-```
+
+# Methoden (und Blocks) geben implizit den Wert des letzten Anweisung zurück.
double(2) #=> 4
-```
-### Klammern sind optional wenn das Ergebnis nicht mehrdeutig ist
-```
+# Klammern sind optional wenn die Anweisung dadurch nicht mehrdeutig wird.
double 3 #=> 6
+
double double 3 #=> 12
+
def sum(x, y)
x + y
end
-```
-### Methoden Parameter werden per Komma getrennt
-```
+# Die Argumente einer Methode werden durch ein Komma getrennt.
sum 3, 4 #=> 7
+
sum sum(3, 4), 5 #=> 12
-```
-## yield
-### Alle Methoden haben einen impliziten, optionalen block Parameter
-### Dieser wird mit dem Schlüsselword "yield" aufgerufen
-```
+# yield
+# Alle Methoden haben implizit einen optionalen block Parameter.
+# Dieser kann durch das Schlüsselwort 'yield' ausgeführt werden.
def surround
puts '{'
yield
puts '}'
end
-surround { puts 'hello world' }
-```
-## Einen Block kann man auch einer Methoden übergeben
-### "&" kennzeichnet die Referenz zum übergebenen Block
-```
+surround { puts 'hallo Welt' }
+
+#=> {
+#=> hallo Welt
+#=> }
+
+# Blocks können in ein 'Proc' Objekt umgewandelt werden.
+# Dieses ist eine Art Container um den Block und erlaubt ihn an eine
+# andere Methode zu übergeben, ihn in einen anderen Gültigkeitsbereicht
+# einzubinden oder ihn andersweitig zu verändern.
+# Am häufigsten findet man dies bei Parameterlisten von Methoden, in Form
+# eines letzten '&block' Parameters, der den Block – wenn es einen gibt –
+# entgegen nimmt und ihn in ein 'Proc' umwandelt. Die Benennung '&block' ist
+# hier nur eine Konvention; es würde genauso mit '&pineapple' funktionieren.
def guests(&block)
- block.call 'some_argument'
+ block.class #=> Proc
+ block.call(4)
end
-```
-### Eine Liste von Parametern kann man auch übergeben,
-### Diese wird in ein Array konvertiert
-### "*" kennzeichnet dies.
-```
+# Die 'call' Methode eines Proc ist ganz ähnlich zum Aufruf von 'yield', wenn
+# ein Block vorhanden ist. Die Argumente, die 'call' übergeben werden, werden
+# als Argumente and den Block weitergereicht.
+
+guests { |n| "Du hast #{n} Gäste." }
+# => "Du hast 4 Gäste."
+
+# Du kannst eine Liste von Argumenten übergeben, die dann in ein Array
+# umgewandelt werden. Dafür gibt es den splat-Operator (`*`).
def guests(*array)
array.each { |guest| puts guest }
end
-```
+
+# Destrukturierung
+
+# Ruby destrukturiert Arrays automatisch beim Zuweisen mehrerer Variablen.
+a, b, c = [1, 2, 3]
+a #=> 1
+b #=> 2
+c #=> 3
+
+# In manchen Fällen will man den splat-Operator (`*`) verwenden um ein Array in
+# eine Liste zu destrukturieren.
+ranked_competitors = ["John", "Sally", "Dingus", "Moe", "Marcy"]
+
+def best(first, second, third)
+ puts "Gewinner sind #{first}, #{second} und #{third}."
+end
+
+best *ranked_competitors.first(3) #=> Gewinner sind John, Sally and Dingus.
+
+# Der splat-Operator kann auch in Parametern verwendet werden.
+def best(first, second, third, *others)
+ puts "Gewinner sind #{first}, #{second} und #{third}."
+ puts "Es gab #{others.count} andere Teilnehmer."
+end
+
+best *ranked_competitors
+#=> Gewinner sind John, Sally und Dingus.
+#=> Es gab 2 andere Teilnehmer.
+
+# Per Konvention enden alle Methoden, die einen Wahrheitswert zurück geben, mit einem
+# Fragezeichen.
+5.even? #=> false
+5.odd? #=> true
+
+# Wenn ein Methodenname mit einem Ausrufezeichen endet, dann tut diese Methode
+# per Konvention etwas Destruktives, wie z.B. das aufrufende Objekt zu
+# verändern.
+# Viele Mehtoden haben eine !-Version um eine direkte Änderung zu machen und
+# eine Nicht-!-Version, die ein neues Objekt mit den Veränderungen zurück gibt.
+company_name = "Dunder Mifflin"
+company_name.upcase #=> "DUNDER MIFFLIN"
+company_name #=> "Dunder Mifflin"
+# Diesmal verändern wir company_name direkt.
+company_name.upcase! #=> "DUNDER MIFFLIN"
+company_name #=> "DUNDER MIFFLIN"
+
# Klassen
-## Werden mit dem class Schlüsselwort definiert
-```
+
+# Du kannst eine Klasse mit dem Schlüsselwort 'class' definieren.
class Human
-```
-### Konstruktor bzw. Initializer
-```
+ # Eine Klassenvariable. Sie wird von allen Instanzen einer Klasse geteilt.
+ @@species = 'H. sapiens'
+
+ # Konstruktor bzw. Initializer
def initialize(name, age = 0)
- # Assign the argument to the "name" instance variable for the instance
+ # Weise das Argument der Instanzvariable 'name' zu.
@name = name
- # If no age given, we will fall back to the default in the arguments list.
+ # Wenn kein 'age' angegeben wurde wird der Standartwert aus der Argumentenlist verwendet.
@age = age
end
-```
-### setter Methode
-```
+ # Setter Methode
def name=(name)
@name = name
end
-```
-### getter Methode
-```
+
+ # Getter Methode
def name
@name
end
-```
-#### getter können mit der attr_accessor Methode vereinfacht definiert werden
-```
+ # Getter & Setter können auch kürzer mit der attr_accessor Methode erstellt werden.
attr_accessor :name
- # Getter/setter methods can also be created individually like this
+
+ # Getter & Setter Methoden können auch einzeln erstellt werden.
attr_reader :name
attr_writer :name
- # A class method uses self to distinguish from instance methods.
- # It can only be called on the class, not an instance.
+
+ # Eine Klassenmethode unterscheidet sich durch ein 'self' von einer
+ # Instanzmethode.
+ # Sie kann nur auf der Klasse und nicht auf einer Instanz der Klasse
+ # aufgerufen werden.
def self.say(msg)
puts msg
end
+
def species
@@species
end
end
-```
-## Eine Klasse instanziieren
-```
+# Instanziieren einer Klasse
jim = Human.new('Jim Halpert')
dwight = Human.new('Dwight K. Schrute')
-```
-## Methodenaufrufe
-```
+# Du kannst die Methoden des erstellten Objekts aufrufen.
jim.species #=> "H. sapiens"
jim.name #=> "Jim Halpert"
jim.name = "Jim Halpert II" #=> "Jim Halpert II"
jim.name #=> "Jim Halpert II"
dwight.species #=> "H. sapiens"
dwight.name #=> "Dwight K. Schrute"
-```
-## Eine Klassenmethode aufrufen
-```
+# Aufrufen einer Klassenmethode
Human.say('Hi') #=> "Hi"
-```
-## Variable Gültigkeit
-### Variablen die mit "$" starten, gelten global
-```
-$var = "I'm a global var"
+# Der Gültigkeitsbereich einer Variablen wird durch ihren Namen definiert.
+# Variablen, die mit $ beginnen sind global gültig.
+$var = "Ich bin eine globale Variable"
defined? $var #=> "global-variable"
-```
-### Variablen die mit "@" starten, gelten für die Instanz
-```
-@var = "I'm an instance var"
+# Variablen, die mit @ beginnen, sind innerhalb einer Instanz gültig.
+@var = "Ich bin eine Instanzvariable"
defined? @var #=> "instance-variable"
-```
-### Variablen die mit "@@" starten, gelten für die Klasse
-```
-@@var = "I'm a class var"
+# Variablen, die mit @@ beginnen, sind für die Klasse gültig.
+@@var = "Ich bin eine Klassenvariable"
defined? @@var #=> "class variable"
-```
-### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten
-```
-Var = "I'm a constant"
+# Variablen, die mit einem Großbuchstaben beginnen, sind Konstanten
+Var = "Ich bin eine Konstante"
defined? Var #=> "constant"
-```
-## Class ist auch ein Objekt
-### Hat also auch Instanzvariablen
-### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt.
+# Class ist in Ruby auch ein Objekt. Deshalb kann eine Klasse Instanzvariablen
+# haben. Eine Klassenvariable wird zwischen der Klasse und all ihren
+# Ableitungen geteilt.
-### Basis Klasse
-```
+# Basis Klasse
class Human
@@foo = 0
+
def self.foo
@@foo
end
+
def self.foo=(value)
@@foo = value
end
end
-```
-### Abgeleitete Klasse
-```
+# Abgeleitete Klasse
class Worker < Human
end
-Human.foo # 0
-Worker.foo # 0
-Human.foo = 2 # 2
-Worker.foo # 2
-```
-### Eine Klasseninstanzvariable wird nicht geteilt
-```
+Human.foo #=> 0
+Worker.foo #=> 0
+
+Human.foo = 2
+Worker.foo #=> 2
+
+# Ableitungen einer Klasse haben keinen Zugriff auf eine Eine Klassen-Instanzvariable.
class Human
@bar = 0
+
def self.bar
@bar
end
+
def self.bar=(value)
@bar = value
end
end
-```
-```
+
class Doctor < Human
end
-```
-```
-Human.bar # 0
-Doctor.bar # nil
-```
-```
+
+Human.bar #=> 0
+Doctor.bar #=> nil
+
module ModuleExample
def foo
'foo'
end
end
-```
-### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden
-### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden
-```
+
+# Ein Einbinden (include) eines Moduls bindet seine Methoden an die Instanzen
+# der Klasse.
+# Ein Erweitern (extend) eines Moduls bindet seine Methoden an die Klasse
+# selbst.
class Person
include ModuleExample
end
-```
-```
+
class Book
extend ModuleExample
end
-```
-```
-Person.foo # => NoMethodError: undefined method `foo' for Person:Class
-Person.new.foo # => 'foo'
-Book.foo # => 'foo'
-Book.new.foo # => NoMethodError: undefined method `foo'
-```
-### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird
-```
- module ConcernExample
- def self.included(base)
- base.extend(ClassMethods)
- base.send(:include, InstanceMethods)
- end
- module ClassMethods
- def bar
- 'bar'
- end
- end
- module InstanceMethods
- def qux
- 'qux'
- end
+
+Person.foo #=> NoMethodError: undefined method `foo' for Person:Class
+Person.new.foo #=> "foo"
+Book.foo #=> "foo"
+Book.new.foo #=> NoMethodError: undefined method `foo'
+
+
+# Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird.
+module ConcernExample
+ def self.included(base)
+ base.extend(ClassMethods)
+ base.send(:include, InstanceMethods)
+ end
+
+ module ClassMethods
+ def bar
+ 'bar'
end
end
- class Something
- include ConcernExample
+
+ module InstanceMethods
+ def qux
+ 'qux'
+ end
end
-```
-```
-Something.bar # => 'bar'
-Something.qux # => NoMethodError: undefined method `qux'
-Something.new.bar # => NoMethodError: undefined method `bar'
-Something.new.qux # => 'qux'
+end
+
+class Something
+ include ConcernExample
+end
+
+Something.bar #=> "bar"
+Something.qux #=> NoMethodError: undefined method `qux'
+Something.new.bar #=> NoMethodError: undefined method `bar'
+Something.new.qux #=> "qux"
```
-## Weiterführende Hinweise
+## Weitere Links
-//EN
+_(z.T. auf Englisch)_
-- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
-- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
+- [Offizielle Ruby Website](https://www.ruby-lang.org/de/)
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Eine Variante dieses Dokuments mit in-Browser Challenges.
+- [RubyMonk](https://rubymonk.com/) - Lerne Ruby mit einer Reihe interaktiver Tutorials.
+- [Offizielle Dokumentation](http://ruby-doc.org/core)
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
-- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
-- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Eine ältere [freie Ausgabe](http://ruby-doc.com/docs/ProgrammingRuby/) ist online verfügbar.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Ein von der Community erstellter Ruby coding style guide.
+- [Try Ruby](http://tryruby.org) - Lerne die Grundlagen der Ruby Programmiersprache, interaktiv im Browser.
diff --git a/el-gr/vim-gr.html.markdown b/el-gr/vim-gr.html.markdown
new file mode 100644
index 00000000..679a5488
--- /dev/null
+++ b/el-gr/vim-gr.html.markdown
@@ -0,0 +1,267 @@
+---
+category: tool
+tool: vim
+contributors:
+ - ["RadhikaG", "https://github.com/RadhikaG"]
+filename: LearnVim.txt
+lang: el-gr
+---
+
+
+[Vim](http://www.vim.org)
+To (Vi IMproved) είναι ένας κλώνος του δημοφιλούς vi editor για Unix.
+Είναι ένας text editor σχεδιασμένος για ταχύτητα και αυξημένη παραγωγικότητα,
+και υπάρχει σχεδόν σε όλα τα Unix-based συστήματα. Έχει διάφορα keybindings
+(συντομεύσεις πλήκτρων) για να πλοηγούμαστε γρήγορα σε συγκεκριμένα σημεία ενός αρχείου,
+καθώς και για γρήγορη επεξεργασία.
+
+## Τα βασικά της πλοήγησης στον Vim
+
+```
+ vim <filename> # Άνοιξε το <filename> στον vim
+ :help <topic> # Άνοιξε το built-in βοήθημα για το <topic> αν υπάρχει
+ :q # Βγες από τον vim
+ :w # Αποθήκευσε το τρέχον αρχείο
+ :wq # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim
+ ZZ # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim
+ :q! # Βγες χωρίς αποθήκευση
+ # ! *αναγκάζει* το :q να εκτελεστεί, γι αυτό βγαίνει χωρίς saving
+ :x # Ίδιο με το wq αλλά πιο σύντομο
+
+ u # Undo
+ CTRL+R # Redo
+
+ h # Μετακινήσου κατά ένα χαρακτήρα αριστερά
+ j # Μετακινήσου μια γραμμή κάτω
+ k # Μετακινήσου μια γραμμή πάνω
+ l # Μετακινήσου μια γραμμή δεξιά
+
+ Ctrl+B # Πήγαινε μία οθόνη πίσω
+ Ctrl+F # Πήγαινε μία οθόνη μπροστά
+ Ctrl+U # Πήγαινε μισή οθόνη πίσω
+ Ctrl+D # Πήγαινε μισή οθόνη μπροστά
+
+ # Μετακινήσεις στην ίδια γραμμή
+
+ 0 # Πήγαινε στην αρχή της γραμμής
+ $ # Πήγαινε στο τέλος της γραμμής
+ ^ # Πήγαινε στον πρώτο μη κενό χαρακτήρα της γραμμής
+
+ # Αναζήτηση στο κείμενο
+
+ /word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης μετά τον cursor
+ ?word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης πριν τον cursor
+ n # Μετακινεί τον cursor στην επόμενη εμφάνιση της λέξης
+ N # Μετακινεί τον cursor στην προηγούμενη εμφάνιση της λέξης
+
+ :%s/foo/bar/g # άλλαξε το 'foo' σε 'bar' σε κάθε γραμμή του αρχείου
+ :s/foo/bar/g # άλλαξε το 'foo' σε 'bar' στην τρέχουσα γραμμή
+
+ # Άλματα σε χαρακτήρες
+
+ f<character> # Άλμα μπροστά και προσγείωση στο επόμενο <character>
+ t<character> # Άλμα μπροστά και προσγείωση αμέσως πριν το προηγούμενο <character>
+
+ # Για παράδειγμα,
+ f< # Άλμα μπροστά και προσγείωση σε <
+ t< # Άλμα μπροστά και προσγείωση αμέσως πριν <
+
+ # Μετακινήσεις κατά λέξεις
+
+ w # Πήγαινε μια λέξη μπροστά
+ b # Πήγαινε μια λέξη πίσω
+ e # Πήγαινε στο τέλος της λέξης στην οποία είσαι
+
+ # Άλλοι χαρακτήρες για να τριγυρνάμε
+
+ gg # Πήγαινε στην αρχή του αρχείου
+ G # Πήγαινε στο τέλος του αρχείου
+ :NUM # Πήγαινε στη γραμμή με αριθμό NUM (οποιοσδήποτε αριθμός)
+ H # Πήγαινε στην κορυφή της σελίδας
+ M # Πήγαινε στην μέση της σελίδας
+ L # Πήγαινε στο κάτω άκρο της σελίδας
+```
+
+## Help docs:
+Το Vim έχει built-in help documentation που μπορείς να δεις με `:help <topic>`.
+Για παράδειγμα το `:help navigation` θα σου εμφανίσει documentation σχετικό με
+το πως να πλοηγείσαι στο αρχείο!
+
+To `:help` μπορεί να χρησιμοποιηθεί και χωρίς option. Αυτό θα εμφανίσει το default
+help dialog που σκοπεύει να κάνει το vim πιο προσιτό σε αρχάριους!
+
+## Modes:
+
+O Vim στηρίζεται στο concept των **modes**.
+
+- Command Mode - ο vim εκκινεί σε αυτό mode, χρησιμοποιείται για πλοήγηση και εντολές
+- Insert Mode - χρησιμοποιείται για να κάνουμε αλλαγές στα αρχεία
+- Visual Mode - χρησιμοποιείται για να υπογραμμίζουμε κείμενα και να κάνουμε διάφορα σε αυτά
+- Ex Mode - χρησιμοποιείται για να πάμε στο κάτω μέρος με το ':' που δίνουμε εντολές
+
+```
+ i # Βάζει το vim σε insert mode, πριν τη θέση cursor
+ a # Βάζει το vim σε insert mode, μετά τη θέση cursor
+ v # βάζει τον vim σε visual mode
+ : # Βάζει τον vim σε ex mode
+ <esc> # φεύγει από όποιο mode είμαστε και πάει σε command mode
+
+ # Αντιγραφή-Επικόληση κειμένου
+
+ y # Yank (κάνε copy) ό,τι είναι επιλεγμένο
+ yy # Yank την γραμμή στην οποία είσαι
+ d # διάγραψε ό,τι είναι επιλεγμένο
+ dd # Διάγραψε τη γραμμή στην οποία είσαι
+ p # Κάνε Paste το αντεγραμένο κείμενο μετά την θέση του cursor
+ P # Κάνε Paste το αντεγραμένο κείμενο πριν την θέση του cursor
+ x # Διάγραψε τον χαρακτήρα που είναι κάτω από τον cursor
+```
+
+## Η 'γραμματική' του Vim
+
+Μπορείς να σκεφτείς τον Vim ως ένα σύνολο εντολών
+σε μορφή 'Verb-Modifier-Noun', όπου
+
+- Verb - η ενέργεια που θες να κάνεις
+- Modifier - πώς κάνεις την ενέργεια
+- Noun - το αντικείμενο που δέχεται την ενέργεια
+
+Μερικά παραδείγματα ''Ρημάτων', 'Modifiers' και 'Ουσιαστικών':
+
+```
+ # 'Ρήματα'
+
+ d # Διάγραψε
+ c # Άλλαξε
+ y # Yank (αντίγραψε)
+ v # Επίλεξε οπτικά
+
+ # 'Modifiers'
+
+ i # Μέσα
+ a # Γύρω
+ NUM # Αριθμός (NUM = οποιοσδήποτε αριθμός)
+ f # Ψάξε κάτι και πήγαινε εκεί που βρίσκεται
+ t # Ψάξε κάτι και πήγαινε πριν από εκεί που βρίσκεται
+ / # Βρες κάποιο string μετά από τον cursor
+ ? # Βρες κάποιο string πριν τον cursor
+
+ # 'Ουσιαστικά'
+
+ w # Λέξη
+ s # Πρόταση
+ p # Παράγραφος
+ b # Block
+
+ # Δείγματα 'προτάσεων' ή εντολών
+
+ d2w # Διάγραψε 2 λέξεις
+ cis # Άλλαξε μέσα στην πρώταση
+ yip # Αντίγραψε την παράγραφο στην οποία βρίσκεσαι
+ ct< # Άλλαξε σε <
+ # Άλλαξε το κείμενο από το οποίο είσαι πριν το επόμενο bracketChange the text from where you are to the next open bracket
+ d$ # Διάγραψε μέχρι το τέλος της γραμμής
+```
+
+## Μερικά shortcuts και κόλπα
+
+ <!--TODO: Βάλτε κι άλλα!-->
+```
+ > # Στοίχισε προς τα δεξιά την επιλογή σου κατά ένα block
+ < # Στοίχισε προς τα αριστερά την επιλογή σου κατά ένα block
+ :earlier 15m # Κάνε το αρχείο όπως ήταν πριν 15 λεπτά
+ :later 15m # Ακύρωση για την παραπάνω εντολή
+ ddp # Αντάλλαξε τις θέσεις διαδοχικών γραμμών
+ . # Επανάλαβε την προηγούμενη ενέργεια
+ :w !sudo tee % # Σώσε το τρέχον αρχείο ως root
+ :set syntax=c # Κάνε syntax highlighting για τη γλώσσα c
+ :sort # Ταξινόμησε όλες τις γραμμές
+ :sort! # Ταξινόμησε ανάποδα όλες τις γραμμές (αύξουσα σειρά)
+ :sort u # Ταξινόμησε όλες τις γραμμές και διάγραψε τις διπλές γραμμές
+ ~ # Άλλαξε τα κεφαλαία σε μικρά στο επιλεγμένο κείμενο
+ u # Το επιλεγμένο κείμενο να γίνει πεζά γράμματα
+ U # Το επιλεγμένο κείμενο να γίνει κεφαλαία γράμματα
+
+ # Fold text
+ zf # Διπλώνει (συμπιέζει τις γραμμές σε μία) το επιλεγμένο κείμενο
+ zo # Ξεδιπλώνει το επιλεγμένο fold
+ zc # Κλείνει το επιλεγμένο fold
+ zR # Ανοίγει όλα τα folds
+ zM # Κλείνει όλα τα folds
+```
+
+## Macros
+
+Τα macros βασικά είναι καταγραφή ενεργειών.
+Όταν ξεικάς να καταγράφεις ένα macro καταγράφονται **όλες** οι ενέργεις και οι
+εντολές που χρησιμοποιείς, μέχρι να σταματήσεις την καταγραφή. Όταν καλείς ένα macro,
+εκτελείται πάλι η ίδια σειρά από ενέργειες και εντολές στο επιλεγμένο κείμενο.
+
+```
+ qa # Ξεκίνα να καταγράφεις ένα macro που θα ονομαστεί 'a'
+ q # Σταμάτα την καταγραφή
+ @a # Τρέξε το macro
+```
+
+### Configuring ~/.vimrc
+
+Το αρχείο .vimrc μπορεί να χρησιμοποιηθεί για να κάνεις configure το Vim στο startup.
+
+Εδώ βλέπουμε δείγμα ενός ~/.vimrc file:
+
+```
+" Example ~/.vimrc
+" 2015.10
+
+" Required for vim to be iMproved
+set nocompatible
+
+" Determines filetype from name to allow intelligent auto-indenting, etc.
+filetype indent plugin on
+
+" Enable syntax highlighting
+syntax on
+
+" Better command-line completion
+set wildmenu
+
+" Use case insensitive search except when using capital letters
+set ignorecase
+set smartcase
+
+" When opening a new line and no file-specific indenting is enabled,
+" keep same indent as the line you're currently on
+set autoindent
+
+" Display line numbers on the left
+set number
+
+" Indentation options, change according to personal preference
+
+" Number of visual spaces per TAB
+set tabstop=4
+
+" Number of spaces in TAB when editing
+set softtabstop=4
+
+" Number of spaces indented when reindent operations (>> and <<) are used
+set shiftwidth=4
+
+" Convert TABs to spaces
+set expandtab
+
+" Enable intelligent tabbing and spacing for indentation and alignment
+set smarttab
+```
+
+### Αναφορές
+
+[Vim | Home](http://www.vim.org/index.php)
+
+`$ vimtutor`
+
+[A vim Tutorial and Primer](https://danielmiessler.com/study/vim/)
+
+[What are the dark corners of Vim your mom never told you about? (Stack Overflow thread)](http://stackoverflow.com/questions/726894/what-are-the-dark-corners-of-vim-your-mom-never-told-you-about)
+
+[Arch Linux Wiki](https://wiki.archlinux.org/index.php/Vim)
diff --git a/elixir.html.markdown b/elixir.html.markdown
index 0b717ca6..0226ecaf 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -457,3 +457,4 @@ Agent.update(my_agent, fn colors -> ["blue" | colors] end)
* [Elixir Cheat Sheet](https://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
* ["Learn You Some Erlang for Great Good!"](https://learnyousomeerlang.com/) by Fred Hebert
* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong
+* [Introduction to Elixir](https://learn-elixir.com/)
diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown
index 644182ff..76e9b6e6 100644
--- a/es-es/perl-es.html.markdown
+++ b/es-es/perl-es.html.markdown
@@ -11,9 +11,9 @@ translators:
lang: es-es
---
-Perl 5 es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
+Perl es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
-Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
+Perl corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
```perl
# Comentarios de una sola línea con un carácter hash
@@ -31,7 +31,7 @@ Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores cen
my $animal = "camello";
my $respuesta = 42;
-# Los valores escalares pueden ser cadenas de caracteres, números enteros o
+# Los valores escalares pueden ser cadenas de caracteres, números enteros o
# de punto flotante; Perl automáticamente los convertirá como sea requerido
## Arreglos
@@ -52,7 +52,7 @@ my %color_fruta = (
# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata)
-# Los tipos de datos más complejos se pueden construir utilizando
+# Los tipos de datos más complejos se pueden construir utilizando
# referencias, las cuales le permiten construir listas y hashes dentro
# de listas y hashes
@@ -61,7 +61,7 @@ my %color_fruta = (
# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes
if ( $var ) {
...;
-} elsif ( $var eq 'bar' ) {
+} elsif ( $var eq 'bar' ) {
...;
} else {
...;
@@ -98,7 +98,7 @@ foreach (@array) {
#### Expresiones regulares
-# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
+# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
# Sin embargo, resumiendo:
@@ -113,7 +113,7 @@ $a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en
#### Archivos y E/S
-# Puede abrir un archivo para obtener datos o escribirlos utilizando la
+# Puede abrir un archivo para obtener datos o escribirlos utilizando la
# función "open()"
open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!";
@@ -122,7 +122,7 @@ open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!";
# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>".
# En contexto escalar, leer una sola línea desde el gestor de archivo, y
-# en contexto de lista, leer el archivo completo en donde asigna
+# en contexto de lista, leer el archivo completo en donde asigna
# cada línea a un elemento de la lista
my $linea = <$entrada>;
diff --git a/es-es/perl6-es.html.markdown b/es-es/raku-es.html.markdown
index bf3ae65e..e916d0fd 100644
--- a/es-es/perl6-es.html.markdown
+++ b/es-es/raku-es.html.markdown
@@ -1,8 +1,8 @@
---
name: perl6
category: language
-language: perl6
-filename: perl6-es.p6
+language: Raku
+filename: learnraku-es.raku
contributors:
- ["vendethiel", "http://github.com/vendethiel"]
- ["Samantha McVey", "https://cry.nu"]
@@ -11,10 +11,10 @@ translators:
lang: es-es
---
-Perl 6 es un lenguaje de programación altamente capaz y con características
+Raku es un lenguaje de programación altamente capaz y con características
abundantes para hacerlo el lenguage ideal por los próximos 100 años.
-El compilador primario de Perl 6 se llama [Rakudo](http://rakudo.org), el cual
+El compilador primario de Raku se llama [Rakudo](http://rakudo.org), el cual
se ejecuta en JVM y en [MoarVM](http://moarvm.com).
Meta-nota: dos signos de números (##) son usados para indicar párrafos,
@@ -26,7 +26,7 @@ mientras que un solo signo de número (#) indica notas.
# Un comentario de una sola línea comienza con un signo de número
#`(
- Comentarios multilíneas usan #` y signos de encerradura tales
+ Comentarios multilíneas usan #` y signos de encerradura tales
como (), [], {}, 「」, etc.
)
```
@@ -34,28 +34,28 @@ mientras que un solo signo de número (#) indica notas.
## Variables
```perl6
-## En Perl 6, se declara una variable lexical usando `my`
+## En Raku, se declara una variable lexical usando `my`
my $variable;
-## Perl 6 tiene 3 tipos básicos de variables: escalares, arrays, y hashes.
+## Raku tiene 3 tipos básicos de variables: escalares, arrays, y hashes.
```
### Escalares
```perl6
-# Un escalar representa un solo valor. Variables escalares comienzan
+# Un escalar representa un solo valor. Variables escalares comienzan
# con un `$`
my $str = 'Cadena';
-# Las comillas inglesas ("") permiten la intepolación (lo cual veremos
+# Las comillas inglesas ("") permiten la intepolación (lo cual veremos
# luego):
my $str2 = "Cadena";
## Los nombres de variables pueden contener pero no terminar con comillas
-## simples y guiones. Sin embargo, pueden contener
+## simples y guiones. Sin embargo, pueden contener
## (y terminar con) guiones bajos (_):
my $nombre'de-variable_ = 5; # Esto funciona!
-my $booleano = True; # `True` y `False` son valores booleanos en Perl 6.
+my $booleano = True; # `True` y `False` son valores booleanos en Raku.
my $inverso = !$booleano; # Puedes invertir un booleano con el operador prefijo `!`
my $bool-forzado = so $str; # Y puedes usar el operador prefijo `so` que
# convierte su operador en un Bool
@@ -70,7 +70,7 @@ my $bool-forzado = so $str; # Y puedes usar el operador prefijo `so` que
my @array = 'a', 'b', 'c';
# equivalente a:
my @letras = <a b c>; # array de palabras, delimitado por espacios.
- # Similar al qw de perl5, o el %w de Ruby.
+ # Similar al qw de perl, o el %w de Ruby.
my @array = 1, 2, 3;
say @array[2]; # Los índices de un array empiezan por el 0 -- Este es
@@ -83,7 +83,7 @@ say "Interpola todos los elementos de un array usando [] : @array[]";
@array[0, 1] = 5, 6; # Asigna varios valores
my @llaves = 0, 2;
-@array[@llaves] = @letras; # Asignación usando un array que contiene valores
+@array[@llaves] = @letras; # Asignación usando un array que contiene valores
# índices
say @array; #=> a 6 b
```
@@ -93,19 +93,19 @@ say @array; #=> a 6 b
```perl6
## Un hash contiene parejas de llaves y valores.
## Puedes construir un objeto Pair usando la sintaxis `LLave => Valor`.
-## Tablas de hashes son bien rápidas para búsqueda, y son almacenadas
+## Tablas de hashes son bien rápidas para búsqueda, y son almacenadas
## sin ningún orden.
## Ten en cuenta que las llaves son "aplanadas" en contexto de hash, y
## cualquier llave duplicada es deduplicada.
my %hash = 1 => 2,
3 => 4;
-my %hash = foo => "bar", # las llaves reciben sus comillas
+my %hash = foo => "bar", # las llaves reciben sus comillas
# automáticamente.
"some other" => "value", # las comas colgantes estań bien.
;
## Aunque los hashes son almacenados internamente de forma diferente a los
-## arrays, Perl 6 te permite crear un hash usando un array
+## arrays, Raku te permite crear un hash usando un array
## con un número par de elementos fácilmente.
my %hash = <llave1 valor1 llave2 valor2>;
@@ -122,7 +122,7 @@ my %hash = :w(1), # equivalente a `w => 1`
say %hash{'llave1'}; # Puedes usar {} para obtener el valor de una llave
say %hash<llave2>; # Si es una cadena de texto, puedes actualmente usar <>
- # (`{llave1}` no funciona, debido a que Perl 6 no tiene
+ # (`{llave1}` no funciona, debido a que Raku no tiene
# palabras desnudas (barewords en inglés))
```
@@ -133,7 +133,7 @@ say %hash<llave2>; # Si es una cadena de texto, puedes actualmente usar <>
## creadas con la palabra clave `sub`.
sub di-hola { say "¡Hola, mundo!" }
-## Puedes proveer argumentos (tipados). Si especificado,
+## Puedes proveer argumentos (tipados). Si especificado,
## el tipo será chequeado al tiempo de compilación si es posible.
## De lo contrario, al tiempo de ejecución.
sub di-hola-a(Str $nombre) {
@@ -165,7 +165,7 @@ say return-for; # imprime Nil
## Una subrutina puede tener argumentos opcionales:
sub con-opcional($arg?) { # el signo "?" marca el argumento opcional
- say "Podría returnar `(Any)` (valor de Perl parecido al 'null') si no me pasan
+ say "Podría returnar `(Any)` (valor de Perl parecido al 'null') si no me pasan
un argumento, o returnaré mi argumento";
$arg;
}
@@ -173,7 +173,7 @@ con-opcional; # devuelve Any
con-opcional(); # devuelve Any
con-opcional(1); # devuelve 1
-## También puedes proveer un argumento por defecto para
+## También puedes proveer un argumento por defecto para
## cuando los argumentos no son proveídos:
sub hola-a($nombre = "Mundo") {
say "¡Hola, $nombre!";
@@ -190,10 +190,10 @@ sub con-nombre($arg-normal, :$nombrado) {
}
con-nombre(1, nombrado => 6); #=> 7
## Sin embargo, debes tener algo en cuenta aquí:
-## Si pones comillas alrededor de tu llave, Perl 6 no será capaz de verla
+## Si pones comillas alrededor de tu llave, Raku no será capaz de verla
## al tiempo de compilación, y entonces tendrás un solo objeto Pair como
-## un argumento posicional, lo que significa que el siguiente ejemplo
-## falla:
+## un argumento posicional, lo que significa que el siguiente ejemplo
+## falla:
con-nombre(1, 'nombrado' => 6);
con-nombre(2, :nombrado(5)); #=> 7
@@ -205,7 +205,7 @@ sub con-nombre-mandatorio(:$str!) {
}
con-nombre-mandatorio(str => "Mi texto"); #=> Mi texto!
con-nombre-mandatorio; # error al tiempo de ejecución:
- # "Required named parameter not passed"
+ # "Required named parameter not passed"
# ("Parámetro nombrado requerido no proveído")
con-nombre-mandatorio(3);# error al tiempo de ejecución:
# "Too many positional parameters passed"
@@ -226,7 +226,7 @@ sub nombrado-definido(:$def = 5) {
nombrado-definido; #=> 5
nombrado-definido(def => 15); #=> 15
-## Dado que puedes omitir los paréntesis para invocar una función sin
+## Dado que puedes omitir los paréntesis para invocar una función sin
## argumentos, necesitas usar "&" en el nombre para almacenar la función
## `di-hola` en una variable.
my &s = &di-hola;
@@ -240,8 +240,8 @@ sub muchos($principal, *@resto) { #`*@` (slurpy) consumirá lo restante
say @resto.join(' / ') ~ "!";
}
say muchos('Feliz', 'Cumpleaño', 'Cumpleaño'); #=> Feliz / Cumpleaño!
- # Nota que el asterisco (*) no
- # consumió el parámetro frontal.
+ # Nota que el asterisco (*) no
+ # consumió el parámetro frontal.
## Puedes invocar un función con un array usando el
## operador "aplanador de lista de argumento" `|`
@@ -256,12 +256,12 @@ concat3(|@array); #=> a, b, c
## Contenedores
```perl6
-## En Perl 6, valores son actualmente almacenados en "contenedores".
-## El operador de asignación le pregunta al contenedor en su izquierda
+## En Raku, valores son actualmente almacenados en "contenedores".
+## El operador de asignación le pregunta al contenedor en su izquierda
## almacenar el valor a su derecha. Cuando se pasan alrededor, contenedores
## son marcados como inmutables. Esto significa que, en una función, tu
## tendrás un error si tratas de mutar uno de tus argumentos.
-## Si realmente necesitas hacerlo, puedes preguntar por un contenedor
+## Si realmente necesitas hacerlo, puedes preguntar por un contenedor
## mutable usando `is rw`:
sub mutar($n is rw) {
$n++;
@@ -276,7 +276,7 @@ mutar $m; # ¡$n es ahora 43!
## dado que no contenedor ha sido pasado y números enteros son inmutables
## por naturaleza:
-mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
+mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
# pero recibió un valor Int
## Si en cambio quieres una copia, debes usar `is copy`.
@@ -286,7 +286,7 @@ mutar 42; # Parámetro '$n' esperaba un contenedor mutable,
my $x = 42;
sub x-almacena() is rw { $x }
x-almacena() = 52; # En este caso, los paréntesis son mandatorios
- # (porque de otra forma, Perl 6 piensa que la función
+ # (porque de otra forma, Raku piensa que la función
# `x-almacena` es un identificador).
say $x; #=> 52
```
@@ -297,9 +297,9 @@ say $x; #=> 52
```perl6
## - `if`
## Antes de hablar acerca de `if`, necesitamos saber cuales valores son
-## "Truthy" (representa True (verdadero)), y cuales son "Falsey"
-## (o "Falsy") -- representa False (falso). Solo estos valores son
-## Falsey: 0, (), {}, "", Nil, un tipo (como `Str` o`Int`) y
+## "Truthy" (representa True (verdadero)), y cuales son "Falsey"
+## (o "Falsy") -- representa False (falso). Solo estos valores son
+## Falsey: 0, (), {}, "", Nil, un tipo (como `Str` o`Int`) y
## por supuesto False. Todos los valores son Truthy.
if True {
say "¡Es verdadero!";
@@ -316,8 +316,8 @@ unless False {
## También puedes usar sus versiones sufijos seguidas por la palabra clave:
say "Un poco verdadero" if True;
-## - La condicional ternaria, "?? !!" (como `x ? y : z` en otros lenguajes)
-## devuelve $valor-si-verdadera si la condición es verdadera y
+## - La condicional ternaria, "?? !!" (como `x ? y : z` en otros lenguajes)
+## devuelve $valor-si-verdadera si la condición es verdadera y
## $valor-si-falsa si es falsa.
## my $resultado = $valor condición ?? $valor-si-verdadera !! $valor-si-falsa;
@@ -338,21 +338,21 @@ say $edad > 18 ?? "Eres un adulto" !! "Eres menor de 18";
##
## `given` simplemente pone su argumento en `$_` (como un bloque lo haría),
## y `when` lo compara usando el operador de "coincidencia inteligente" (`~~`).
-##
-## Dado que otras construcciones de Perl 6 usan esta variable (por ejemplo,
+##
+## Dado que otras construcciones de Raku usan esta variable (por ejemplo,
## el bucle `for`, bloques, etc), esto se significa que el poderoso `when` no
-## solo se aplica con un `given`, sino que se puede usar en cualquier
+## solo se aplica con un `given`, sino que se puede usar en cualquier
## lugar donde exista una variable `$_`.
given "foo bar" {
say $_; #=> foo bar
- when /foo/ { # No te preocupies acerca de la coincidencia inteligente –
+ when /foo/ { # No te preocupies acerca de la coincidencia inteligente –
# solo ten presente que `when` la usa.
# Esto es equivalente a `if $_ ~~ /foo/`.
say "¡Yay!";
}
when $_.chars > 50 { # coincidencia inteligente con cualquier cosa True es True,
- # i.e. (`$a ~~ True`)
+ # i.e. (`$a ~~ True`)
# por lo tanto puedes también poner condiciones "normales".
# Este `when` es equivalente a este `if`:
# if $_ ~~ ($_.chars > 50) {...}
@@ -373,12 +373,12 @@ given "foo bar" {
## pero también puede ser un bucle for al estilo de C:
loop {
say "¡Este es un bucle infinito!";
- last; # last interrumpe el bucle, como la palabra clave `break`
+ last; # last interrumpe el bucle, como la palabra clave `break`
# en otros lenguajes.
}
loop (my $i = 0; $i < 5; $i++) {
- next if $i == 3; # `next` salta a la siguiente iteración, al igual
+ next if $i == 3; # `next` salta a la siguiente iteración, al igual
# que `continue` en otros lenguajes. Ten en cuenta que
# también puedes usar la condicionales postfix (sufijas)
# bucles, etc.
@@ -391,29 +391,29 @@ for @array -> $variable {
}
## Como vimos con `given`, la variable de una "iteración actual" por defecto
-## es `$_`. Esto significa que puedes usar `when` en un bucle `for` como
+## es `$_`. Esto significa que puedes usar `when` en un bucle `for` como
## normalmente lo harías con `given`.
for @array {
say "he conseguido a $_";
.say; # Esto es también permitido.
- # Una invocación con punto (dot call) sin "tópico" (recibidor) es
- # enviada a `$_` por defecto.
+ # Una invocación con punto (dot call) sin "tópico" (recibidor) es
+ # enviada a `$_` por defecto.
$_.say; # lo mismo de arriba, lo cual es equivalente.
}
for @array {
# Puedes...
- next if $_ == 3; # Saltar a la siguiente iteración (`continue` en
+ next if $_ == 3; # Saltar a la siguiente iteración (`continue` en
# lenguages parecido a C)
- redo if $_ == 4; # Re-hacer la iteración, manteniendo la
+ redo if $_ == 4; # Re-hacer la iteración, manteniendo la
# misma variable tópica (`$_`)
- last if $_ == 5; # Salir fuera del bucle (como `break`
+ last if $_ == 5; # Salir fuera del bucle (como `break`
# en lenguages parecido a C)
}
-## La sintaxis de "bloque puntiagudo" no es específica al bucle for.
-## Es solo una manera de expresar un bloque en Perl 6.
+## La sintaxis de "bloque puntiagudo" no es específica al bucle for.
+## Es solo una manera de expresar un bloque en Raku.
if computación-larga() -> $resultado {
say "El resultado es $resultado";
}
@@ -423,7 +423,7 @@ if computación-larga() -> $resultado {
```perl6
## Dados que los lenguajes de la familia Perl son lenguages basados
-## mayormente en operadores, los operadores de Perl 6 son actualmente
+## mayormente en operadores, los operadores de Raku son actualmente
## subrutinas un poco cómicas en las categorías sintácticas. Por ejemplo,
## infix:<+> (adición) o prefix:<!> (bool not).
@@ -455,7 +455,7 @@ if computación-larga() -> $resultado {
(1, 2) eqv (1, 3);
## - Operador de coincidencia inteligente (smart matching): `~~`
-## Asocia (aliasing en inglés) el lado izquierda a la variable $_
+## Asocia (aliasing en inglés) el lado izquierda a la variable $_
## y después evalúa el lado derecho.
## Aquí algunas comparaciones semánticas comunes:
@@ -464,8 +464,8 @@ if computación-larga() -> $resultado {
'Foo' ~~ 'Foo'; # True si las cadenas de texto son iguales.
12.5 ~~ 12.50; # True si los números son iguales.
-## Regex - Para la comparación de una expresión regular en contra
-## del lado izquierdo. Devuelve un objeto (Match), el cual evalúa
+## Regex - Para la comparación de una expresión regular en contra
+## del lado izquierdo. Devuelve un objeto (Match), el cual evalúa
## como True si el regex coincide con el patrón.
my $obj = 'abc' ~~ /a/;
@@ -475,12 +475,12 @@ say $obj.WHAT; # (Match)
## Hashes
'llave' ~~ %hash; # True si la llave existe en el hash
-## Tipo - Chequea si el lado izquierdo "tiene un tipo" (puede chequear
+## Tipo - Chequea si el lado izquierdo "tiene un tipo" (puede chequear
## superclases y roles)
1 ~~ Int; # True (1 es un número entero)
-## Coincidencia inteligente contra un booleano siempre devuelve ese
+## Coincidencia inteligente contra un booleano siempre devuelve ese
## booleano (y lanzará una advertencia).
1 ~~ True; # True
@@ -502,13 +502,13 @@ False ~~ True; # True
## Esto también funciona como un atajo para `0..^N`:
^10; # significa 0..^10
-## Esto también nos permite demostrar que Perl 6 tiene arrays
+## Esto también nos permite demostrar que Raku tiene arrays
## ociosos/infinitos, usando la Whatever Star:
my @array = 1..*; # 1 al Infinito! `1..Inf` es lo mismo.
say @array[^10]; # puedes pasar arrays como subíndices y devolverá
# un array de resultados. Esto imprimirá
# "1 2 3 4 5 6 7 8 9 10" (y no se quedaré sin memoria!)
-## Nota: Al leer una lista infinita, Perl 6 "cosificará" los elementos que
+## Nota: Al leer una lista infinita, Raku "cosificará" los elementos que
## necesita y los mantendrá en la memoria. Ellos no serán calculados más de
## una vez. Tampoco calculará más elementos de los que necesita.
@@ -517,14 +517,14 @@ say @array[^10]; # puedes pasar arrays como subíndices y devolverá
say join(' ', @array[15..*]); #=> 15 16 17 18 19
## lo que es equivalente a:
say join(' ', @array[-> $n { 15..$n }]);
-## Nota: Si tratas de hacer cualquiera de esos con un array infinito,
+## Nota: Si tratas de hacer cualquiera de esos con un array infinito,
## provocará un array infinito (tu programa nunca terminará)
## Puedes usar eso en los lugares que esperaría, como durante la asignación
## a un array
my @números = ^20;
-## Aquí los números son incrementados por "6"; más acerca del
+## Aquí los números son incrementados por "6"; más acerca del
## operador `...` adelante.
my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99;
@números[5..*] = 3, 9 ... *; # aunque la secuencia es infinita,
@@ -546,7 +546,7 @@ $a && $b && $c; # Devuelve 0, el primer valor que es False
$b || $a; # 1
## Y porque tu lo querrás, también tienes operadores de asignación
-## compuestos:
+## compuestos:
$a *= 2; # multiplica y asigna. Equivalente a $a = $a * 2;
$b %%= 5; # divisible por y asignación. Equivalente $b = $b %% 5;
@array .= sort; # invoca el método `sort` y asigna el resultado devuelto.
@@ -555,8 +555,8 @@ $b %%= 5; # divisible por y asignación. Equivalente $b = $b %% 5;
## ¡Más sobre subrutinas!
```perl6
-## Como dijimos anteriormente, Perl 6 tiene subrutinas realmente poderosas.
-## Veremos unos conceptos claves que la hacen mejores que en cualquier otro
+## Como dijimos anteriormente, Raku tiene subrutinas realmente poderosas.
+## Veremos unos conceptos claves que la hacen mejores que en cualquier otro
## lenguaje :-).
```
@@ -602,14 +602,14 @@ sub fst(*@ [$fst]) { # o simplemente: `sub fst($fst) { ... }`
fst(1); #=> 1
fst(1, 2); # errores con "Too many positional parameters passed"
-## También puedes desestructurar hashes (y clases, las cuales
-## veremos adelante). La sintaxis es básicamente
+## También puedes desestructurar hashes (y clases, las cuales
+## veremos adelante). La sintaxis es básicamente
## `%nombre-del-hash (:llave($variable-para-almacenar))`.
## El hash puede permanecer anónimos si solo necesitas los valores extraídos.
sub llave-de(% (:azul($val1), :red($val2))) {
say "Valores: $val1, $val2.";
}
-## Después invócala con un hash: (necesitas mantener las llaves
+## Después invócala con un hash: (necesitas mantener las llaves
## de los parejas de llave y valor para ser un hash)
llave-de({azul => 'blue', rojo => "red"});
#llave-de(%hash); # lo mismo (para un `%hash` equivalente)
@@ -621,11 +621,11 @@ sub siguiente-indice($n) {
}
my $nuevo-n= siguiente-indice(3); # $nuevo-n es ahora 4
-## Este es cierto para todo, excepto para las construcciones de bucles
+## Este es cierto para todo, excepto para las construcciones de bucles
## (debido a razones de rendimiento): Hay una razón de construir una lista
## si la vamos a desechar todos los resultados.
## Si todavías quieres construir una, puedes usar la sentencia prefijo `do`:
-## (o el prefijo `gather`, el cual veremos luego)
+## (o el prefijo `gather`, el cual veremos luego)
sub lista-de($n) {
do for ^$n { # nota el uso del operador de rango `^` (`0..^N`)
$_ # iteración de bucle actual
@@ -639,19 +639,19 @@ my @list3 = lista-de(3); #=> (0, 1, 2)
```perl6
## Puedes crear una lambda con `-> {}` ("bloque puntiagudo") o `{}` ("bloque")
my &lambda = -> $argumento { "El argumento pasado a esta lambda es $argumento" }
-## `-> {}` y `{}` son casi la misma cosa, excepto que la primerra puede
+## `-> {}` y `{}` son casi la misma cosa, excepto que la primerra puede
## tomar argumentos, y la segunda puede ser malinterpretada como un hash
## por el parseador.
## Podemos, por ejemplo, agregar 3 a cada valor de un array usando map:
my @arraymas3 = map({ $_ + 3 }, @array); # $_ es el argumento implícito
-## Una subrutina (`sub {}`) tiene semánticas diferentes a un
-## bloque (`{}` or `-> {}`): Un bloque no tiene "contexto funcional"
+## Una subrutina (`sub {}`) tiene semánticas diferentes a un
+## bloque (`{}` or `-> {}`): Un bloque no tiene "contexto funcional"
## (aunque puede tener argumentos), lo que significa que si quieres devolver
## algo desde un bloque, vas a returnar desde la función parental. Compara:
sub is-in(@array, $elem) {
- # esto `devolverá` desde la subrutina `is-in`
+ # esto `devolverá` desde la subrutina `is-in`
# Una vez que la condición evalúa a True, el bucle terminará
map({ return True if $_ == $elem }, @array);
}
@@ -685,7 +685,7 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (aquí con `sub`)
### Acerca de tipos...
```perl6
-## Perl 6 es gradualmente tipado. Esto quiere decir que tu especifica el
+## Raku es gradualmente tipado. Esto quiere decir que tu especifica el
## tipo de tus variables/argumentos/devoluciones (return), o puedes omitirlos
## y serán "Any" por defecto.
## Obviamente tienes acceso a algunas tipos básicos, como Int y Str.
@@ -703,7 +703,7 @@ subset EnteroGrande of Int where * > 500;
### Despacho Múltiple (Multiple Dispatch)
```perl6
-## Perl 6 puede decidir que variante de una subrutina invocar basado en el
+## Raku puede decidir que variante de una subrutina invocar basado en el
## tipo de los argumento, o precondiciones arbitrarias, como con un tipo o
## un `where`:
@@ -740,9 +740,9 @@ multi sin_ti-o-contigo {
}
## Esto es muy útil para muchos propósitos, como subrutinas `MAIN` (de las
## cuales hablaremos luego), y hasta el mismo lenguaje la está usando
-## en muchos lugares.
+## en muchos lugares.
##
-## - `is`, por ejemplo, es actualmente un `multi sub` llamado
+## - `is`, por ejemplo, es actualmente un `multi sub` llamado
## `trait_mod:<is>`.
## - `is rw`, es simplemente un despacho a una función con esta signatura:
## sub trait_mod:<is>(Routine $r, :$rw!) {}
@@ -754,7 +754,7 @@ multi sin_ti-o-contigo {
## Ámbito (Scoping)
```perl6
-## En Perl 6, a diferencia de otros lenguajes de scripting, (tales como
+## En Raku, a diferencia de otros lenguajes de scripting, (tales como
## (Python, Ruby, PHP), debes declarar tus variables antes de usarlas. El
## declarador `my`, del cual aprendiste anteriormente, usa "ámbito léxical".
## Hay otros declaradores (`our`, `state`, ..., ) los cuales veremos luego.
@@ -770,7 +770,7 @@ sub externo {
}
outer()(); #=> 'Foo Bar'
-## Como puedes ver, `$archivo-en-ámbito` y `$ámbito-externo`
+## Como puedes ver, `$archivo-en-ámbito` y `$ámbito-externo`
## fueron capturados. Pero si intentaramos usar `$bar` fuera de `foo`,
## la variable estaría indefinida (y obtendrías un error al tiempo de
## compilación).
@@ -779,12 +779,12 @@ outer()(); #=> 'Foo Bar'
## Twigils
```perl6
-## Hay muchos `twigils` especiales (sigilos compuestos) en Perl 6.
-## Los twigils definen el ámbito de las variables.
+## Hay muchos `twigils` especiales (sigilos compuestos) en Raku.
+## Los twigils definen el ámbito de las variables.
## Los twigils * y ? funcionan con variables regulares:
## * Variable dinámica
## ? Variable al tiempo de compilación
-## Los twigils ! y . son usados con los objetos de Perl 6:
+## Los twigils ! y . son usados con los objetos de Raku:
## ! Atributo (miembro de la clase)
## . Método (no una variable realmente)
@@ -820,20 +820,20 @@ di_ambito(); #=> 1 100 Cambiamos el valor de $*ambito_din_2 en invoca_a_di_ambit
```perl6
## Para invocar a un método en un objeto, agrega un punto seguido por el
-## nombre del objeto:
+## nombre del objeto:
## => $object.method
## Las classes son declaradas usando la palabra clave `class`. Los atributos
## son declarados con la palabra clave `has`, y los métodos con `method`.
## Cada atributo que es privado usa el twigil `!`. Por ejemplo: `$!attr`.
-## Atributos públicos inmutables usan el twigil `.` (los puedes hacer
+## Atributos públicos inmutables usan el twigil `.` (los puedes hacer
## mutables con `is rw`).
-## La manera más fácil de recordar el twigil `$.` is comparándolo
+## La manera más fácil de recordar el twigil `$.` is comparándolo
## con como los métodos son llamados.
-## El modelo de objeto de Perl 6 ("SixModel") es muy flexible, y te permite
+## El modelo de objeto de Raku ("SixModel") es muy flexible, y te permite
## agregar métodos dinámicamente, cambiar la semántica, etc ...
-## (no hablaremos de todo esto aquí. Por lo tanto, refiérete a:
-## https://docs.perl6.org/language/objects.html).
+## (no hablaremos de todo esto aquí. Por lo tanto, refiérete a:
+## https://docs.raku.org/language/objects.html).
class Clase-Atrib {
has $.atrib; # `$.atrib` es inmutable.
@@ -858,7 +858,7 @@ class Clase-Atrib {
};
## Crear una nueva instancia de Clase-Atrib con $.atrib asignado con 5:
-## Nota: No puedes asignarle un valor a atrib-privado desde aquí (más de
+## Nota: No puedes asignarle un valor a atrib-privado desde aquí (más de
## esto adelante).
my $class-obj = Clase-Atrib.new(atrib => 5);
say $class-obj.devolver-valor; #=> 5
@@ -870,12 +870,12 @@ $class-obj.otro-atrib = 10; # En cambio, esto funciona porque el atributo
### Herencia de Objeto
```perl6
-## Perl 6 también tiene herencia (junto a herencia múltiple)
+## Raku también tiene herencia (junto a herencia múltiple)
## Mientras los métodos declarados con `method` son heredados, aquellos
## declarados con `submethod` no lo son.
## Submétodos son útiles para la construcción y destrucción de tareas,
## tales como BUILD, o métodos que deben ser anulados por subtipos.
-## Aprenderemos acerca de BUILD más adelante.
+## Aprenderemos acerca de BUILD más adelante.
class Padre {
has $.edad;
@@ -890,7 +890,7 @@ class Padre {
# Herencia usa la palabra clave `is`
class Niño is Padre {
method hablar { say "Goo goo ga ga" }
- # Este método opaca el método `hablar` de Padre.
+ # Este método opaca el método `hablar` de Padre.
# Este niño no ha aprendido a hablar todavía.
}
my Padre $Richard .= new(edad => 40, nombre => 'Richard');
@@ -899,19 +899,19 @@ $Richard.hablar; #=> "Hola, mi nombre es Richard"
## $Richard es capaz de acceder el submétodo; él sabe como decir su nombre.
my Niño $Madison .= new(edad => 1, nombre => 'Madison');
-$Madison.hablar; # imprime "Goo goo ga ga" dado que el método fue cambiado
+$Madison.hablar; # imprime "Goo goo ga ga" dado que el método fue cambiado
# en la clase Niño.
# $Madison.color-favorito # no funciona porque no es heredado
## Cuando se usa `my T $var` (donde `T` es el nombre de la clase), `$var`
## inicia con `T` en si misma, por lo tanto puedes invocar `new` en `$var`.
-## (`.=` es sólo la invocación por punto y el operador de asignación:
+## (`.=` es sólo la invocación por punto y el operador de asignación:
## `$a .= b` es lo mismo que `$a = $a.b`)
## Por ejemplo, la instancia $Richard pudo también haber sido declarada así:
## my $Richard = Padre.new(edad => 40, nombre => 'Richard');
-## También observa que `BUILD` (el método invocado dentro de `new`)
-## asignará propiedades de la clase padre, por lo que puedes pasar
+## También observa que `BUILD` (el método invocado dentro de `new`)
+## asignará propiedades de la clase padre, por lo que puedes pasar
## `val => 5`.
```
@@ -932,7 +932,7 @@ class Item does PrintableVal {
has $.val;
## Cuando se utiliza `does`, un `rol` se mezcla en al clase literalmente:
- ## los métodos y atributos se ponen juntos, lo que significa que una clase
+ ## los métodos y atributos se ponen juntos, lo que significa que una clase
## puede acceder los métodos y atributos privados de su rol (pero no lo inverso!):
method access {
say $!counter++;
@@ -945,17 +945,17 @@ class Item does PrintableVal {
## de su clase hijo/a, pero es un error sin un rol lo hace)
## NOTA: Puedes usar un rol como una clase (con `is ROLE`). En este caso,
- ## métodos serán opacados, dado que el compilador considerará `ROLE`
- ## como una clase.
+ ## métodos serán opacados, dado que el compilador considerará `ROLE`
+ ## como una clase.
}
```
## Excepciones
```perl6
-## Excepciones están construidas al tope de las clases, en el paquete
+## Excepciones están construidas al tope de las clases, en el paquete
## `X` (como `X::IO`).
-## En Perl 6, excepciones son lanzadas automáticamente.
+## En Raku, excepciones son lanzadas automáticamente.
open 'foo'; #=> Failed to open file foo: no such file or directory
## También imprimirá la línea donde el error fue lanzado y otra información
## concerniente al error.
@@ -966,16 +966,16 @@ die 'Error!'; #=> Error!
## O más explícitamente:
die X::AdHoc.new(payload => 'Error!');
-## En Perl 6, `orelse` es similar al operador `or`, excepto que solamente
+## En Raku, `orelse` es similar al operador `or`, excepto que solamente
## coincide con variables indefinidas, en cambio de cualquier cosa
## que evalúa a falso.
-## Valores indefinidos incluyen: `Nil`, `Mu` y `Failure`, también como
+## Valores indefinidos incluyen: `Nil`, `Mu` y `Failure`, también como
## `Int`, `Str` y otros tipos que no han sido inicializados a ningún valor
## todavía.
## Puedes chequear si algo está definido o no usando el método defined:
my $no-inicializada;
say $no-inicializada.defined; #=> False
-## Al usar `orelse`, se desarmará la excepción y creará un alias de dicho
+## Al usar `orelse`, se desarmará la excepción y creará un alias de dicho
## fallo en $_
## Esto evitará que sea automáticamente manejado e imprima una marejada de
## mensajes de errores en la pantalla.
@@ -986,7 +986,7 @@ open 'foo' orelse say "Algo pasó {.exception}";
open 'foo' orelse say "Algo pasó $_"; #=> Algo pasó
#=> Failed to open file foo: no such file or directory
## Ambos ejemplos anteriores funcionan pero en caso de que consigamos un
-## objeto desde el lado izquierdo que no es un fallo, probablemente
+## objeto desde el lado izquierdo que no es un fallo, probablemente
## obtendremos una advertencia. Más abajo vemos como usar `try` y `CATCH`
## para ser más expecíficos con las excepciones que capturamos.
```
@@ -994,8 +994,8 @@ open 'foo' orelse say "Algo pasó $_"; #=> Algo pasó
### Usando `try` y `CATCH`
```perl6
-## Al usar `try` y `CATCH`, puedes contener y manejar excepciones sin
-## interrumpir el resto del programa. `try` asignará la última excepción
+## Al usar `try` y `CATCH`, puedes contener y manejar excepciones sin
+## interrumpir el resto del programa. `try` asignará la última excepción
## a la variable especial `$!`.
## Nota: Esto no tiene ninguna relación con las variables $!.
@@ -1003,12 +1003,12 @@ try open 'foo';
say "Bueno, lo intenté! $!" if defined $!; #=> Bueno, lo intenté! Failed to open file
#foo: no such file or directory
## Ahora, ¿qué debemos hacer si queremos más control sobre la excepción?
-## A diferencia de otros lenguajes, en Perl 6 se pone el bloque `CATCH`
+## A diferencia de otros lenguajes, en Raku se pone el bloque `CATCH`
## *dentro* del bloque a intentar (`try`). Similarmente como $_ fue asignada
## cuando 'disarmamos' la excepción con `orelse`, también usamos $_ en el
## bloque CATCH.
## Nota: ($! es solo asignada *después* del bloque `try`)
-## Por defecto, un bloque `try` tiene un bloque `CATCH` que captura
+## Por defecto, un bloque `try` tiene un bloque `CATCH` que captura
## cualquier excepción (`CATCH { default {} }`).
try { my $a = (0 %% 0); CATCH { say "Algo pasó: $_" } }
@@ -1022,9 +1022,9 @@ try {
when X::AdHoc { say "Error: $_" }
#=>Error: Failed to open file /dir/foo: no such file or directory
- ## Cualquier otra excepción será levantada de nuevo, dado que no
+ ## Cualquier otra excepción será levantada de nuevo, dado que no
## tenemos un `default`.
- ## Básicamente, si un `when`
+ ## Básicamente, si un `when`
## Basically, if a `when` matches (or there's a `default`) marks the
## exception as
## "handled" so that it doesn't get re-thrown from the `CATCH`.
@@ -1032,14 +1032,14 @@ try {
}
}
-## En Perl 6, excepciones poseen ciertas sutilezas. Algunas
-## subrutinas en Perl 6 devuelven un `Failure`, el cual es un tipo de
+## En Raku, excepciones poseen ciertas sutilezas. Algunas
+## subrutinas en Raku devuelven un `Failure`, el cual es un tipo de
## "excepción no levantada". Ellas no son levantadas hasta que tu intentas
-## mirar a sus contenidos, a menos que invoques `.Bool`/`.defined` sobre
+## mirar a sus contenidos, a menos que invoques `.Bool`/`.defined` sobre
## ellas - entonces, son manejadas.
## (el método `.handled` es `rw`, por lo que puedes marcarlo como `False`
## por ti mismo)
-## Puedes levantar un `Failure` usando `fail`. Nota que si el pragma
+## Puedes levantar un `Failure` usando `fail`. Nota que si el pragma
## `use fatal` estás siendo utilizado, `fail` levantará una excepión (como
## `die`).
fail "foo"; # No estamos intentando acceder el valor, por lo tanto no problema.
@@ -1053,27 +1053,27 @@ try {
## También hay otro tipo de excepción: Excepciones de control.
## Esas son excepciones "buenas", las cuales suceden cuando cambias el flujo
## de tu programa, usando operadores como `return`, `next` or `last`.
-## Puedes capturarlas con `CONTROL` (no lista un 100% en Rakudo todavía).
+## Puedes capturarlas con `CONTROL` (no lista un 100% en Rakudo todavía).
```
## Paquetes
```perl6
-## Paquetes son una manera de reusar código. Paquetes son como
-## "espacio de nombres" (namespaces en inglés), y cualquier elemento del
+## Paquetes son una manera de reusar código. Paquetes son como
+## "espacio de nombres" (namespaces en inglés), y cualquier elemento del
## modelo seis (`module`, `role`, `class`, `grammar`, `subset` y `enum`)
-## son paquetes por ellos mismos. (Los paquetes son como el mínimo común
+## son paquetes por ellos mismos. (Los paquetes son como el mínimo común
## denominador)
-## Los paquetes son importantes - especialmente dado que Perl es bien
+## Los paquetes son importantes - especialmente dado que Perl es bien
## reconocido por CPAN, the Comprehensive Perl Archive Nertwork.
## Puedes usar un módulo (traer sus declaraciones al ámbito) con `use`
use JSON::Tiny; # si intalaste Rakudo* o Panda, tendrás este módulo
say from-json('[1]').perl; #=> [1]
-## A diferencia de Perl 5, no deberías declarar paquetes usando
+## A diferencia de Perl, no deberías declarar paquetes usando
## la palabra clave `package`. En vez, usa `class Nombre::Paquete::Aquí;`
-## para declarar una clase, o si solamente quieres exportar
+## para declarar una clase, o si solamente quieres exportar
## variables/subrutinas, puedes usar `module`.
module Hello::World { # forma de llaves
@@ -1083,11 +1083,11 @@ module Hello::World { # forma de llaves
}
unit module Parse::Text; # forma de ámbito de archivo
-grammar Parse::Text::Grammar { # Una gramática (grammar en inglés) es un paquete,
+grammar Parse::Text::Grammar { # Una gramática (grammar en inglés) es un paquete,
# en el cual puedes usar `use`
} # Aprenderás más acerca de gramáticas en la sección de regex
-## Como se dijo anteriormente, cualquier parte del modelo seis es también un
+## Como se dijo anteriormente, cualquier parte del modelo seis es también un
## paquete. Dado que `JSON::Tiny` usa su propia clase `JSON::Tiny::Actions`,
## tu puedes usarla de la manera siguiente:
my $acciones = JSON::Tiny::Actions.new;
@@ -1098,13 +1098,13 @@ my $acciones = JSON::Tiny::Actions.new;
## Declaradores
```perl6
-## En Perl 6, tu obtienes diferentes comportamientos basado en como declaras
+## En Raku, tu obtienes diferentes comportamientos basado en como declaras
## una variable.
## Ya has visto `my` y `has`, ahora exploraremos el resto.
## * las declaraciones `our` ocurren al tiempo `INIT` (ve "Phasers" más abajo)
## Es como `my`, pero también crea una variable paquete.
-## (Todas las cosas relacionadas con paquetes (`class`, `role`, etc) son
+## (Todas las cosas relacionadas con paquetes (`class`, `role`, etc) son
## `our` por defecto)
module Var::Incrementar {
our $nuestra-var = 1; # Nota: No puedes colocar una restricción de tipo
@@ -1132,7 +1132,7 @@ Var::Incrementar::Inc; #=> 3 # Nota como el valor de $nuestra-var fue
Var::Incrementar::no-disponible; #=> Could not find symbol '&no-disponible'
## * `constant` (ocurre al tiempo `BEGIN`)
-## Puedes usar la palabra clave `constant` para declarar una
+## Puedes usar la palabra clave `constant` para declarar una
## variable/símbolo al tiempo de compilación:
constant Pi = 3.14;
constant $var = 1;
@@ -1151,11 +1151,11 @@ sub aleatorio-fijo {
aleatorio-fijo for ^10; # imprimirá el mismo número 10 veces
## Nota, sin embargo, que ellas existen separadamente en diferentes contextos.
-## Si declaras una función con un `state` dentro de un bucle, recreará la
+## Si declaras una función con un `state` dentro de un bucle, recreará la
## variable por cada iteración del bucle. Observa:
for ^5 -> $a {
sub foo {
- state $valor = rand; # Esto imprimirá un valor diferente
+ state $valor = rand; # Esto imprimirá un valor diferente
# por cada valor de `$a`
}
for ^5 -> $b {
@@ -1165,11 +1165,11 @@ for ^5 -> $a {
}
```
-## Phasers
+## Phasers
```perl6
-## Un phaser en Perl 6 es un bloque que ocurre a determinados puntos de tiempo
-## en tu programa. Se les llama phaser porque marca un cambio en la fase de
+## Un phaser en Raku es un bloque que ocurre a determinados puntos de tiempo
+## en tu programa. Se les llama phaser porque marca un cambio en la fase de
## de tu programa. Por ejemplo, cuando el programa es compilado, un bucle
## for se ejecuta, dejas un bloque, o una excepción se levanta.
## (¡`CATCH` es actualmente un phaser!)
@@ -1191,13 +1191,13 @@ END { say "Se ejecuta al tiempo de ejecución, " ~
"tan tarde como sea posible, una sola vez" }
## * Phasers de bloques
-ENTER { say "[*] Se ejecuta cada vez que entra en un bloque, " ~
+ENTER { say "[*] Se ejecuta cada vez que entra en un bloque, " ~
"se repite en bloques de bucle" }
-LEAVE { say "Se ejecuta cada vez que abandona un bloque, incluyendo " ~
+LEAVE { say "Se ejecuta cada vez que abandona un bloque, incluyendo " ~
"cuando una excepción ocurre. Se repite en bloques de bucle"}
PRE {
- say "Impone una precondición a cada entrada de un bloque, " ~
+ say "Impone una precondición a cada entrada de un bloque, " ~
"antes que ENTER (especialmente útil para bucles)";
say "Si este bloque no returna un valor truthy, " ~
"una excepción del tipo X::Phaser::PrePost será levantada.";
@@ -1209,7 +1209,7 @@ for 0..2 {
}
POST {
- say "Impone una postcondAsserts a poscondición a la salida de un bloque, " ~
+ say "Impone una postcondAsserts a poscondición a la salida de un bloque, " ~
"después de LEAVE (especialmente útil para bucles)";
say "Si este bloque no returna un valor truthy, " ~
"una excepción del tipo X::Phaser::PrePost será levantada, como con PRE.";
@@ -1250,14 +1250,14 @@ sub do-db-stuff {
## Prefijos de sentencias
```perl6
-## Los prefijos de sentencias actúan como los phasers: Ellos afectan el
+## Los prefijos de sentencias actúan como los phasers: Ellos afectan el
## comportamiento del siguiente código.
## Debido a que son ejecutados en línea con el código ejecutable, ellos
## se escriben en letras minúsculas. (`try` and `start` están teoréticamente
## en esa lista, pero serán explicados en otra parte)
## Nota: Ningunos de estos (excepto `start`) necesitan las llaves `{` y `}`.
-## - `do` (el cual ya viste) - ejecuta un bloque o una sentencia como un
+## - `do` (el cual ya viste) - ejecuta un bloque o una sentencia como un
## término.
## Normalmente no puedes usar una sentencia como un valor (o término):
##
@@ -1289,7 +1289,7 @@ say join ',', gather if False {
## - `eager` - Evalúa una sentencia ávidamente (forza contexto ávido)
## No intentes esto en casa:
##
-## eager 1..*; # esto probablemente se colgará por un momento
+## eager 1..*; # esto probablemente se colgará por un momento
## # (y podría fallar...).
##
## Pero considera lo siguiente:
@@ -1302,13 +1302,13 @@ constant tres-veces = eager gather for ^3 { say take $_ }; #=> 0 1 2
## Iterables
```perl6
-## En Perl 6, los iterables son objetos que pueden ser iterados similar
-## a la construcción `for`.
+## En Raku, los iterables son objetos que pueden ser iterados similar
+## a la construcción `for`.
## `flat`, aplana iterables:
say (1, 10, (20, 10) ); #=> (1 10 (20 10)) Nota como la agrupación se mantiene
say (1, 10, (20, 10) ).flat; #=> (1 10 20 10) Ahora el iterable es plano
-## - `lazy` - Aplaza la evaluación actual hasta que el valor sea requirido
+## - `lazy` - Aplaza la evaluación actual hasta que el valor sea requirido
## (forza contexto perezoso)
my @lazy-array = (1..100).lazy;
say @lazy-array.is-lazy; #=> True # Chequea por "pereza" con el método `is-lazy`.
@@ -1333,7 +1333,7 @@ quietly { warn 'Esto es una advertencia!' }; #=> No salida
## ¡Todo el mundo ama los operadores! Tengamos más de ellos.
## La lista de precedencia puede ser encontrada aquí:
-## https://docs.perl6.org/language/operators#Operator_Precedence
+## https://docs.raku.org/language/operators#Operator_Precedence
## Pero primero, necesitamos un poco de explicación acerca
## de la asociatividad:
@@ -1356,7 +1356,7 @@ $a ! $b ! $c; # con asociatividad de lista `!`, esto es `infix:<>`
## Okay, has leído todo esto y me imagino que debería mostrarte
## algo interesante.
## Te mostraré un pequeño secreto (o algo no tan secreto):
-## En Perl 6, todos los operadores son actualmente solo subrutinas.
+## En Raku, todos los operadores son actualmente solo subrutinas.
## Puedes declarar un operador como declaras una subrutina:
sub prefix:<ganar>($ganador) { # se refiere a las categorías de los operadores
@@ -1374,14 +1374,14 @@ sub postfix:<!>(Int $n) {
}
say 5!; #=> 120
# Operadores sufijos (postfix) van *directamente* después del témino.
- # No espacios en blanco. Puedes usar paréntesis para disambiguar,
+ # No espacios en blanco. Puedes usar paréntesis para disambiguar,
# i.e. `(5!)!`
sub infix:<veces>(Int $n, Block $r) { # infijo va en el medio
for ^$n {
$r(); # Necesitas los paréntesis explícitos para invocar la función
- # almacenada en la variable `$r`. De lo contrario, te estaría
+ # almacenada en la variable `$r`. De lo contrario, te estaría
# refiriendo a la variable (no a la función), como con `&r`.
}
}
@@ -1399,33 +1399,33 @@ say [5]; #=> 3125
# un circunfijo va alrededor. De nuevo, no espacios en blanco.
sub postcircumfix:<{ }>(Str $s, Int $idx) {
- ## un pos-circunfijo es
+ ## un pos-circunfijo es
## "después de un término y alrededor de algo"
$s.substr($idx, 1);
}
say "abc"{1}; #=> b
# depués del término `"abc"`, y alrededor del índice (1)
-## Esto es de gran valor -- porque todo en Perl 6 usa esto.
+## Esto es de gran valor -- porque todo en Raku usa esto.
## Por ejemplo, para eliminar una llave de un hash, tu usas el adverbio
## `:delete` (un simple argumento con nombre debajo):
%h{$llave}:delete;
## es equivalente a:
-postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
+postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
# operadores de esta forma)
-## ¡*Todos* usan los mismos bloques básicos!
+## ¡*Todos* usan los mismos bloques básicos!
## Categorías sintácticas (prefix, infix, ...), argumentos nombrados
## (adverbios), ... - usados para construir el lenguaje - están al alcance
## de tus manos y disponibles para ti.
-## (obviamente, no se te recomienda que hagas un operador de *cualquier
+## (obviamente, no se te recomienda que hagas un operador de *cualquier
## cosa* -- Un gran poder conlleva una gran responsabilidad.)
```
### Meta-operadores!
```perl6
-## ¡Prepárate! Prepárate porque nos estamos metiendo bien hondo
-## en el agujero del conejo, y probablemente no querrás regresar a
+## ¡Prepárate! Prepárate porque nos estamos metiendo bien hondo
+## en el agujero del conejo, y probablemente no querrás regresar a
## otros lenguajes después de leer esto.
## (Me imagino que ya no quieres a este punto).
## Meta-operadores, como su nombre lo sugiere, son operadores *compuestos*.
@@ -1434,14 +1434,14 @@ postcircumfix:<{ }>(%h, $llave, :delete); # (puedes invocar
## * El meta-operador reduce (reducir)
## Es un meta-operador prefijo que toman una función binaria y
## una o varias listas. Sino se pasa ningún argumento,
-## returna un "valor por defecto" para este operador
+## returna un "valor por defecto" para este operador
## (un valor sin significado) o `Any` si no hay ningún valor.
##
-## De lo contrario, remueve un elemento de la(s) lista(s) uno a uno, y
+## De lo contrario, remueve un elemento de la(s) lista(s) uno a uno, y
## aplica la función binaria al último resultado (o al primer elemento de
## la lista y el elemento que ha sido removido).
##
-## Para sumar una lista, podrías usar el meta-operador "reduce" con `+`,
+## Para sumar una lista, podrías usar el meta-operador "reduce" con `+`,
## i.e.:
say [+] 1, 2, 3; #=> 6
## es equivalente a `(1+2)+3`
@@ -1461,20 +1461,20 @@ say [+] (); #=> 0
# valores sin significado, dado que N*1=N y N+0=N.
say [//]; #=> (Any)
# No hay valor por defecto para `//`.
-## También puedes invocarlo con una función de tu creación usando
+## También puedes invocarlo con una función de tu creación usando
## los dobles corchetes:
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; #=> 6
## * El meta-operador zip
-## Este es un meta-operador infijo que también puede ser usado como un
+## Este es un meta-operador infijo que también puede ser usado como un
## operador "normal". Toma una función binaria opcional (por defecto, solo
-## crear un par), y remueve un valor de cada array e invoca su función
+## crear un par), y remueve un valor de cada array e invoca su función
## binaria hasta que no tenga más elementos disponibles. Al final, returna
## un array con todos estos nuevos elementos.
-(1, 2) Z (3, 4); # ((1, 3), (2, 4)), dado que por defecto, la función
+(1, 2) Z (3, 4); # ((1, 3), (2, 4)), dado que por defecto, la función
# crea un array.
-1..3 Z+ 4..6; # (5, 7, 9), usando la función personalizada infix:<+>
+1..3 Z+ 4..6; # (5, 7, 9), usando la función personalizada infix:<+>
## Dado que `Z` tiene asociatividad de lista (ve la lista más arriba),
## puedes usarlo en más de una lista
@@ -1487,13 +1487,13 @@ say [[&add]] 1, 2, 3; #=> 6
## Y para terminar la lista de operadores:
## * El operador secuencia
-## El operador secuencia es uno de la más poderosas características de
-## Perl 6: Está compuesto, en la izquierda, de la lista que quieres que
-## Perl 6 use para deducir (y podría incluir una clausura), y en la derecha,
-## un valor o el predicado que dice cuando parar (o Whatever para una
+## El operador secuencia es uno de la más poderosas características de
+## Raku: Está compuesto, en la izquierda, de la lista que quieres que
+## Raku use para deducir (y podría incluir una clausura), y en la derecha,
+## un valor o el predicado que dice cuando parar (o Whatever para una
## lista infinita perezosa).
my @list = 1, 2, 3 ... 10; # deducción básica
-#my @list = 1, 3, 6 ... 10; # esto muere porque Perl 6 no puede deducir el final
+#my @list = 1, 3, 6 ... 10; # esto muere porque Raku no puede deducir el final
my @list = 1, 2, 3 ...^ 10; # como con rangos, puedes excluir el último elemento
# (la iteración cuando el predicado iguala).
my @list = 1, 3, 9 ... * > 30; # puedes usar un predicado
@@ -1505,8 +1505,8 @@ my @fib = 1, 1, *+* ... *; # lista infinita perezosa de la serie fibonacci,
my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalene a lo de arriba)
my @fib = 1, 1, { $^a + $^b } ... *; #(... también equivalene a lo de arriba)
## $a and $b siempre tomarán el valor anterior, queriendo decir que
-## ellos comenzarán con $a = 1 y $b = 1 (valores que hemos asignado
-## de antemano). Por lo tanto, $a = 1 y $b = 2 (resultado del anterior $a+$b),
+## ellos comenzarán con $a = 1 y $b = 1 (valores que hemos asignado
+## de antemano). Por lo tanto, $a = 1 y $b = 2 (resultado del anterior $a+$b),
## etc.
say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
@@ -1519,29 +1519,29 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
## Expresiones Regulares
```perl6
-## Estoy seguro que has estado esperando por esta parte. Bien, ahora que
-## sabes algo acerca de Perl 6, podemos comenzar. Primeramente, tendrás
-## que olvidarte acerca de "PCRE regexps" (perl-compatible regexps)
+## Estoy seguro que has estado esperando por esta parte. Bien, ahora que
+## sabes algo acerca de Raku, podemos comenzar. Primeramente, tendrás
+## que olvidarte acerca de "PCRE regexps" (perl-compatible regexps)
## (expresiones regulares compatible de perl).
##
## IMPORTANTE: No salte esto porque ya sabes acerca de PCRE. Son totalmente
-## distintos. Algunas cosas son las mismas (como `?`, `+`, y `*`) pero
+## distintos. Algunas cosas son las mismas (como `?`, `+`, y `*`) pero
## algunas veces la semántica cambia (`|`). Asegúrate de leer esto
## cuidadosamente porque podrías trospezarte sino lo haces.
##
-## Perl 6 tiene muchas características relacionadas con RegExps. Después de
+## Raku tiene muchas características relacionadas con RegExps. Después de
## todo, Rakudo se parsea a si mismo. Primero vamos a estudiar la sintaxis
## por si misma, después hablaremos acerca de gramáticas (parecido a PEG),
-## las diferencias entre los declaradores `token`, `regex`, y `rule` y
+## las diferencias entre los declaradores `token`, `regex`, y `rule` y
## mucho más.
-## Nota aparte: Todavía tienes acceso a los regexes PCRE usando el
+## Nota aparte: Todavía tienes acceso a los regexes PCRE usando el
## mofificador `:P5` (Sin embargo, no lo discutiremos en este tutorial).
##
-## En esencia, Perl 6 implementa PEG ("Parsing Expression Grammars")
+## En esencia, Raku implementa PEG ("Parsing Expression Grammars")
## ("Parseado de Expresiones de Gramáticas") nativamente. El orden jerárquico
-## para los parseos ambiguos es determinado por un examen multi-nivel de
+## para los parseos ambiguos es determinado por un examen multi-nivel de
## desempate:
-## - La coincidencia de token más larga. `foo\s+` le gana a `foo`
+## - La coincidencia de token más larga. `foo\s+` le gana a `foo`
## (por 2 o más posiciones)
## - El prefijo literal más largo. `food\w*` le gana a `foo\w*` (por 1)
## - Declaración desde la gramática más derivada a la menos derivada
@@ -1550,48 +1550,48 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
say so 'a' ~~ /a/; #=> True
say so 'a' ~~ / a /; #=> True # ¡Más legible con los espacios!
-## Nota al lector (del traductor):
+## Nota al lector (del traductor):
## Como pudiste haber notado, he decidido traducir "match" y sus diferentes
-## formas verbales como "coincidir" y sus diferentes formas. Cuando digo que
+## formas verbales como "coincidir" y sus diferentes formas. Cuando digo que
## un regex (o regexp) coincide con cierto texto, me refiero a que el regex
## describe cierto patrón dentro del texto. Por ejemplo, el regex "cencia"
-## coincide con el texto "reminiscencia", lo que significa que dentro del
+## coincide con el texto "reminiscencia", lo que significa que dentro del
## texto aparece ese patrón de caracteres (una `c`, seguida de una `e`,
-## (seguida de una `n`, etc.)
+## (seguida de una `n`, etc.)
-## En todos nuestros ejemplos, vamos a usar el operador de
-## "coincidencia inteligente" contra una expresión regular ("regexp" or
+## En todos nuestros ejemplos, vamos a usar el operador de
+## "coincidencia inteligente" contra una expresión regular ("regexp" or
## "regex" de aquí en adelante). Estamos convirtiendo el resultado usando `so`,
## pero en efecto, está devolviendo un objeto Match. Ellos saben como responder
-## a la indexación de lista, indexación de hash, y devolver la cadena de
+## a la indexación de lista, indexación de hash, y devolver la cadena de
## texto coincidente.
-## Los resultados de la coincidencia están disponible como `$/` (en
+## Los resultados de la coincidencia están disponible como `$/` (en
## ámbito implícito lexical). También puedes usar las variables de captura
## las cuales comienzan con 0:
## `$0`, `$1', `$2`...
##
-## Nota que `~~` no hace un chequeo de inicio/final (es decir,
+## Nota que `~~` no hace un chequeo de inicio/final (es decir,
## el regexp puede coincider con solo un carácter de la cadena de texto).
## Explicaremos luego como hacerlo.
-## En Perl 6, puedes tener un carácter alfanumérico como un literal,
+## En Raku, puedes tener un carácter alfanumérico como un literal,
## todo lo demás debe escaparse usando una barra invertida o comillas.
-say so 'a|b' ~~ / a '|' b /; # `True`. No sería lo mismo si no se escapara `|`
+say so 'a|b' ~~ / a '|' b /; # `True`. No sería lo mismo si no se escapara `|`
say so 'a|b' ~~ / a \| b /; # `True`. Otra forma de escaparlo
-## El espacio en blanco actualmente no se significa nada en un regexp,
+## El espacio en blanco actualmente no se significa nada en un regexp,
## a menos que uses el adverbio `:s` (`:sigspace`, espacio significante).
say so 'a b c' ~~ / a b c /; #=> `False`. Espacio no significa nada aquí.
say so 'a b c' ~~ /:s a b c /; #=> `True`. Agregamos el modificador `:s` aquí.
-## Si usamos solo un espacio entre cadenas de texto en un regexp, Perl 6
+## Si usamos solo un espacio entre cadenas de texto en un regexp, Raku
## nos advertirá:
say so 'a b c' ~~ / a b c /; #=> 'False' # Espacio no significa nada aquí.
## Por favor usa comillas o el modificador :s (:sigspace) para suprimir
-## esta advertencia, omitir el espacio, o cambiar el espaciamiento. Para
-## arreglar esto y hacer los espacios menos ambiguos, usa por lo menos
+## esta advertencia, omitir el espacio, o cambiar el espaciamiento. Para
+## arreglar esto y hacer los espacios menos ambiguos, usa por lo menos
## dos espacios entre las cadenas de texto o usa el adverbio `:s`.
-## Como vimos anteriormente, podemos incorporar `:s` dentro de los
+## Como vimos anteriormente, podemos incorporar `:s` dentro de los
## delimitadores de barras. También podemos ponerlos fuera de ellos si
## especificamos `m` for `match` (coincidencia):
say so 'a b c' ~~ m:s/a b c/; #=> `True`
@@ -1603,7 +1603,7 @@ say so 'abc' ~~ m[a b c]; #=> `True`
## minúsculas y mayúsculas:
say so 'ABC' ~~ m:i{a b c}; #=> `True`
-## Sin embargo, es importante para como los modificadores son aplicados
+## Sin embargo, es importante para como los modificadores son aplicados
## (lo cual verás más abajo)...
## Cuantificando - `?`, `+`, `*` y `**`.
@@ -1612,7 +1612,7 @@ so 'ac' ~~ / a b c /; # `False`
so 'ac' ~~ / a b? c /; # `True`, la "b" coincidió (apareció) 0 veces.
so 'abc' ~~ / a b? c /; # `True`, la "b" coincidió 1 vez.
-## ... Como debes saber, espacio en blancos son importante porque
+## ... Como debes saber, espacio en blancos son importante porque
## determinan en que parte del regexp es el objetivo del modificador:
so 'def' ~~ / a b c? /; # `False`. Solamente la `c` es opcional
so 'def' ~~ / a b? c /; # `False`. Espacio en blanco no es significante
@@ -1642,7 +1642,7 @@ so 'abbbbbbc' ~~ / a b**3..* c /; # `True` (rangos infinitos no son un problem
## - `<[]>` - Clases de carácteres
## Las clases de carácteres son equivalentes a las clases `[]` de PCRE,
-## pero usan una sintaxis de Perl 6:
+## pero usan una sintaxis de Raku:
say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'
## Puedes usar rangos:
@@ -1663,7 +1663,7 @@ so 'foo' ~~ / <-[ f o ]> + /; # False
## ... y componerlos:
so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (cualquier letra excepto f y o)
so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letra excepto f and o)
-so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
+so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
# parte de la izquierda)
```
@@ -1671,7 +1671,7 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (el signo + no reemplaza la
```perl6
## Grupo: Puedes agrupar partes de tu regexp con `[]`.
-## Estos grupos *no son* capturados (como con `(?:)` en PCRE).
+## Estos grupos *no son* capturados (como con `(?:)` en PCRE).
so 'abc' ~~ / a [ b ] c /; # `True`. El agrupamiento no hace casi nada
so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
## La línea anterior returna `True`.
@@ -1680,15 +1680,15 @@ so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
## Pero esto no va demasiado lejos, porque no podemos actualmente obtener
## devuelta el patrón que coincidió.
-## Captura: Podemos actualmente *capturar* los resultados del regexp,
+## Captura: Podemos actualmente *capturar* los resultados del regexp,
## usando paréntesis.
so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (usando `so`
# aquí, `$/` más abajo)
-## Ok. Comenzando con las explicaciones de grupos. Como dijimos,
+## Ok. Comenzando con las explicaciones de grupos. Como dijimos,
### nuestra objeto `Match` está disponible en la variable `$/`:
-say $/; # Imprimirá algo extraño (explicaremos luego) o
- # "Nil" si nada coincidió
+say $/; # Imprimirá algo extraño (explicaremos luego) o
+ # "Nil" si nada coincidió
## Como dijimos anteriormente, un objeto Match tiene indexación de array:
say $/[0]; #=> 「ABC」 「ABC」
@@ -1696,15 +1696,15 @@ say $/[0]; #=> 「ABC」 「ABC」
# Aquí, tenemos un array de ellos.
say $0; # Lo mismo que lo anterior.
-## Nuestra captura es `$0` porque es la primera y única captura en el
-## regexp. Podrías estarte preguntando porque un array y la respuesta es
+## Nuestra captura es `$0` porque es la primera y única captura en el
+## regexp. Podrías estarte preguntando porque un array y la respuesta es
## simple: Algunas capturas (indezadas usando `$0`, `$/[0]` o una nombrada)
## será un array si y solo si puedes tener más de un elemento.
## (Así que, con `*`, `+` y `**` (cualquiera los operandos), pero no con `?`).
## Usemos algunos ejemplos para ver como funciona:
## Nota: Pusimos A B C entre comillas para demostrar que el espacio en blanco
-## entre ellos no es significante. Si queremos que el espacio en blanco
+## entre ellos no es significante. Si queremos que el espacio en blanco
## *sea* significante, podemos utilizar el modificador `:sigspace`.
so 'fooABCbar' ~~ / foo ( "A" "B" "C" )? bar /; # `True`
say $/[0]; #=> 「ABC」
@@ -1718,22 +1718,22 @@ say $0.WHAT; #=> (Array)
# Un cuantificador específico siempre capturará un Array,
# puede ser un rango o un valor específico (hasta 1).
-## Las capturas son indezadas por anidación. Esto quiere decir que un grupo
-## dentro de un grup estará anidado dentro de su grupo padre: `$/[0][0]`,
+## Las capturas son indezadas por anidación. Esto quiere decir que un grupo
+## dentro de un grup estará anidado dentro de su grupo padre: `$/[0][0]`,
## para este código:
'hello-~-world' ~~ / ( 'hello' ( <[ \- \~ ]> + ) ) 'world' /;
say $/[0].Str; #=> hello~
say $/[0][0].Str; #=> ~
-## Esto se origina de un hecho bien simple: `$/` no contiene cadenas de
-## texto, números enteros o arrays sino que solo contiene objetos Match.
-## Estos objetos contienen los métodos `.list`, `.hash` y `.Str`. (Pero
-## también puedes usar `match<llave>` para accesar un hash y `match[indice]`
+## Esto se origina de un hecho bien simple: `$/` no contiene cadenas de
+## texto, números enteros o arrays sino que solo contiene objetos Match.
+## Estos objetos contienen los métodos `.list`, `.hash` y `.Str`. (Pero
+## también puedes usar `match<llave>` para accesar un hash y `match[indice]`
## para accesar un array.
say $/[0].list.perl; #=> (Match.new(...),).list
# Podemos ver que es una lista de objetos Match.
- # Estos contienen un montón de información: dónde la
- # coincidencia comenzó o terminó, el "ast"
+ # Estos contienen un montón de información: dónde la
+ # coincidencia comenzó o terminó, el "ast"
# (chequea las acciones más abajo), etc.
# Verás capturas nombradas más abajo con las gramáticas.
@@ -1743,9 +1743,9 @@ so 'abc' ~~ / a [ b | y ] c /; # `True`. o "b" o "y".
so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## La diferencia entre este `|` y el otro al que estás acustombrado es LTM.
-## LTM significa "Longest Token Matching", traducido libremente como
+## LTM significa "Longest Token Matching", traducido libremente como
## "Coincidencia de Token Más Larga". Esto significa que el motor ("engine")
-## siempre intentará coindidir tanto como sea posible en la cadena de texto.
+## siempre intentará coindidir tanto como sea posible en la cadena de texto.
## Básicamente, intentará el patrón más largo que concuerde con el regexp.
'foo' ~~ / fo | foo /; # `foo` porque es más largo.
## Para decidir cual parte es la "más larga", primero separa el regex en
@@ -1759,19 +1759,19 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## anteriores, aserciones de código, y otras cosas que tradicionalmente no pueden
## ser representadas por regexes normales.
##
-## Entonces, todas las alternativas se intentan al mismo tiempo, y la
+## Entonces, todas las alternativas se intentan al mismo tiempo, y la
## más larga gana.
## Ejemplos:
## DECLARATIVO | PROCEDIMENTAL
/ 'foo' \d+ [ <subrule1> || <subrule2> ] /;
## DECLARATIVO (grupos anidados no son un problema)
/ \s* [ \w & b ] [ c | d ] /;
-## Sin embargo, las clausuras y la recursión (de regexes nombrados)
+## Sin embargo, las clausuras y la recursión (de regexes nombrados)
## son procedimentales.
## ... Hay más reglas complicadas, como la especifidad (los literales ganan
## son las clases de caracteres)
+
-## Nota: la primera coincidencia `or` todavía existen, pero ahora se
+## Nota: la primera coincidencia `or` todavía existen, pero ahora se
## deletrea `||`
'foo' ~~ / fo || foo /; # `fo` ahora.
```
@@ -1779,19 +1779,19 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviamente suficiente...
## Extra: la subrutina MAIN
```perl6
-## La subrutina `MAIN` se invoca cuando tu ejecuta un archivo de Perl 6
-## directamente. Es realmente poderosa porque Perl 6 actualmente parsea
-## los argumentos y los pasas a la subrutina. También maneja argumentos
+## La subrutina `MAIN` se invoca cuando tu ejecuta un archivo de Raku
+## directamente. Es realmente poderosa porque Raku actualmente parsea
+## los argumentos y los pasas a la subrutina. También maneja argumentos
## nombrados (`--foo`) y hasta autogenerará un `--help`.
sub MAIN($nombre) { say "¡Hola, $nombre!" }
## Esto produce:
-## $ perl6 cli.pl
+## $ raku cli.pl
## Uso:
## t.pl <nombre>
-## Y dado que una subrutina regular en Perl 6, puedes tener múltiples
+## Y dado que una subrutina regular en Raku, puedes tener múltiples
## despachos:
-## (usando un "Bool" por un argumento nombrado para que podamos hacer
+## (usando un "Bool" por un argumento nombrado para que podamos hacer
## `--replace` a cambio de `--replace=1`)
subset File of Str where *.IO.d; # convierte a un objeto IO para chequear si
# un archivo existe
@@ -1800,7 +1800,7 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
## Esto produce:
-## $ perl6 cli.pl
+## $ raku cli.pl
## Uso:
## t.pl [--replace] add <key> <value>
## t.pl remove <key>
@@ -1814,7 +1814,7 @@ multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
### Lista de cosas
```perl6
-## Consideramos que por ahora ya sabes lo básico de Perl 6.
+## Consideramos que por ahora ya sabes lo básico de Raku.
## Esta sección es solo para listar algunas operaciones comunes
## las cuales no están en la "parte principal" del tutorial.
@@ -1825,13 +1825,13 @@ multi MAIN('import', File, Str :$as) { ... } # omitiendo parámetros nombrados
## (los cuales representan los números -1, 0 o +1).
1 <=> 4; # comparación de orden para caracteres numéricos
'a' leg 'b'; # comparación de orden para cadenas de texto
-$obj eqv $obj2; # comparación de orden usando la semántica eqv
+$obj eqv $obj2; # comparación de orden usando la semántica eqv
## * Ordenación genérica
3 before 4; # True
'b' after 'a'; # True
-## * Operador (por defecto) de circuito corto
+## * Operador (por defecto) de circuito corto
## Al igual que `or` y `||`, pero devuelve el primer valor *defined*
## (definido):
say Any // Nil // 0 // 5; #=> 0
@@ -1843,9 +1843,9 @@ say True ^^ False; #=> True
## * Flip Flop
## Los operadores flip flop (`ff` y `fff`, equivalente a `..`/`...` en P5)
## son operadores que toman dos predicados para evalualarlos:
-## Ellos son `False` hasta que su lado izquierdo devuelve `True`, entonces
+## Ellos son `False` hasta que su lado izquierdo devuelve `True`, entonces
## son `True` hasta que su lado derecho devuelve `True`.
-## Como los rangos, tu puedes excluir la iteración cuando se convierte en
+## Como los rangos, tu puedes excluir la iteración cuando se convierte en
## `True`/`False` usando `^` en cualquier lado.
## Comencemos con un ejemplo:
for <well met young hero we shall meet later> {
@@ -1861,25 +1861,25 @@ for <well met young hero we shall meet later> {
}
## Esto imprimirá "young hero we shall meet" (exluyendo "met"):
## el flip-flop comenzará devolviendo `True` cuando primero encuentra "met"
-## (pero no returnará `False` por "met" dabido al `^` al frente de `ff`),
+## (pero no returnará `False` por "met" dabido al `^` al frente de `ff`),
## hasta que ve "meet", lo cual es cuando comenzará devolviendo `False`.
## La diferencia entre `ff` (al estilo de awk) y `fff` (al estilo de sed)
-## es que `ff` probará su lado derecho cuando su lado izquierdo cambia
+## es que `ff` probará su lado derecho cuando su lado izquierdo cambia
## a `True`, y puede returnar a `False` inmediamente (*excepto* que será
-## `True` por la iteración con la cual coincidió). Por lo contrario,
-## `fff` esperará por la próxima iteración para intentar su lado
+## `True` por la iteración con la cual coincidió). Por lo contrario,
+## `fff` esperará por la próxima iteración para intentar su lado
## derecho, una vez que su lado izquierdo ha cambiado:
.say if 'B' ff 'B' for <A B C B A>; #=> B B
# porque el lado derecho se puso a prueba
# directamente (y returnó `True`).
# Las "B"s se imprimen dadó que coincidió
- # en ese momento (returnó a `False`
+ # en ese momento (returnó a `False`
# inmediatamente).
.say if 'B' fff 'B' for <A B C B A>; #=> B C B
# El lado derecho no se puso a prueba
# hasta que `$_` se convirtió en "C"
- # (y por lo tanto no coincidió
+ # (y por lo tanto no coincidió
# inmediamente).
## Un flip-flop puede cambiar estado cuantas veces se necesite:
@@ -1901,35 +1901,35 @@ for (1, 3, 60, 3, 40, 60) { # Nota: los paréntesis son superfluos aquí
## que no pasará la primera vez:
for <a b c> {
.say if * ^ff *; # el flip-flop es `True` y nunca returna a `False`,
- # pero el `^` lo hace *que no se ejecute* en la
+ # pero el `^` lo hace *que no se ejecute* en la
# primera iteración
#=> b c
}
-## - `===` es la identidad de valor y usa `.WHICH`
+## - `===` es la identidad de valor y usa `.WHICH`
## en los objetos para compararlos.
-## - `=:=` es la identidad de contenedor y usa `VAR()`
+## - `=:=` es la identidad de contenedor y usa `VAR()`
## en los objetos para compararlos.
```
Si quieres ir más allá de lo que se muestra aquí, puedes:
- - Leer la [documentación de Perl 6](https://docs.perl6.org/). Esto es un recurso
- grandioso acerca de Perl 6. Si estás buscando por algo en particular, usa la
+ - Leer la [documentación de Raku](https://docs.raku.org/). Esto es un recurso
+ grandioso acerca de Raku. Si estás buscando por algo en particular, usa la
barra de búsquedas. Esto te dará un menú de todas las páginas concernientes
a tu término de búsqueda (¡Es mucho mejor que usar Google para encontrar
- documentos acerca de Perl 6!)
- - Leer el [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). Este es
- un gran recurso de fragmentos de código de Perl 6 y explicaciones. Si la documentación
+ documentos acerca de Raku!)
+ - Leer el [Raku Advent Calendar](https://rakuadventcalendar.wordpress.com/). Este es
+ un gran recurso de fragmentos de código de Raku y explicaciones. Si la documentación
no describe algo lo suficientemente bien, puedes encontrar información más detallada
aquí. Esta información puede ser un poquito más antigua pero hay muchos ejemplos y
- explicaciones. Las publicaciones fueron suspendidas al final del 2015 cuando
- el lenguaje fue declarado estable y Perl 6.c fue lanzado.
- - Unirte a `#perl6` en `irc.freenode.net`. Las personas aquí son siempre serviciales.
- - Chequear la [fuente de las funciones y clases de Perl 6
- ](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo está principalmente
- escrito en Perl 6 (con mucho de NQP, "Not Quite Perl" ("No Perl Todavía"), un
- subconjunto de Perl 6 que es más fácil de implementar y optimizar).
- - Leer [documentos acerca del diseño del lenguaje](http://design.perl6.org).
+ explicaciones. Las publicaciones fueron suspendidas al final del 2015 cuando
+ el lenguaje fue declarado estable y Raku.c fue lanzado.
+ - Unirte a `#raku` en `irc.freenode.net`. Las personas aquí son siempre serviciales.
+ - Chequear la [fuente de las funciones y clases de Raku
+ ](https://github.com/rakudo/rakudo/tree/master/src/core.c). Rakudo está principalmente
+ escrito en Raku (con mucho de NQP, "Not Quite Perl" ("No Perl Todavía"), un
+ subconjunto de Raku que es más fácil de implementar y optimizar).
+ - Leer [documentos acerca del diseño del lenguaje](http://design.raku.org).
Estos explican P6 desde la perspectiva de un implementador, lo cual es bastante
interesante.
diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown
index e737b7aa..e073bcf5 100644
--- a/fr-fr/perl-fr.html.markdown
+++ b/fr-fr/perl-fr.html.markdown
@@ -10,9 +10,9 @@ translators:
- ["Matteo Taroli", "http://www.matteotaroli.be"]
lang: fr-fr
---
-Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
+Perl est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement.
-Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
+Perl fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et
est autant adapté à un prototypage rapide qu'à des projets de grande envergure.
```perl
diff --git a/git.html.markdown b/git.html.markdown
index aa96c90a..a40ef01b 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -82,12 +82,12 @@ pushed to other repositories, or not!
### Branch
A branch is essentially a pointer to the last commit you made. As you go on
-committing, this pointer will automatically update to point the latest commit.
+committing, this pointer will automatically update to point to the latest commit.
### Tag
A tag is a mark on specific point in history. Typically people use this
-functionality to mark release points (v1.0, and so on)
+functionality to mark release points (v1.0, and so on).
### HEAD and head (component of .git dir)
diff --git a/groovy.html.markdown b/groovy.html.markdown
index 89ca973a..0d589c10 100644
--- a/groovy.html.markdown
+++ b/groovy.html.markdown
@@ -184,7 +184,7 @@ class Foo {
Methods with optional parameters
*/
-// A mthod can have default values for parameters
+// A method can have default values for parameters
def say(msg = 'Hello', name = 'world') {
"$msg $name!"
}
diff --git a/it-it/sql-it.html.markdown b/it-it/sql-it.html.markdown
new file mode 100644
index 00000000..7db2eec1
--- /dev/null
+++ b/it-it/sql-it.html.markdown
@@ -0,0 +1,112 @@
+---
+language: SQL
+filename: learnsql-it.sql
+contributors:
+ - ["Bob DuCharme", "http://bobdc.com/"]
+translators:
+ - ["Christian Grasso", "https://grasso.io"]
+lang: it-it
+---
+
+Structured Query Language (SQL) è un linguaggio standard ISO per la creazione e la gestione
+di database organizzati in un insieme di tabelle. Le diverse implementazioni aggiungono
+spesso le proprie estensioni al linguaggio base ([confronto tra le diverse implementazioni](http://troels.arvin.dk/db/rdbms/))
+
+Le diverse implementazioni forniscono inoltre un prompt per inserire in modo interattivo i comandi
+o eseguire il contenuto di uno script.
+
+I comandi di seguito lavorano sul [database di esempio MySQL](https://dev.mysql.com/doc/employee/en/)
+disponibile su [GitHub](https://github.com/datacharmer/test_db). I file .sql contengono liste di comandi
+simili a quelli mostrati di seguito, che creano e riempiono delle tabelle con dati di un'azienda fittizia.
+Il comando per eseguire questi script può variare in base all'implementazione in uso.
+
+
+```sql
+-- I commenti iniziano con due trattini. Ogni comando va terminato con il punto e virgola
+
+-- SQL è case-insensitive per quanto riguarda i comandi; in genere si
+-- preferisce scriverli in maiuscolo per distinguerli dai nomi di
+-- database, tabelle e colonne
+
+-- Crea ed elimina un database. I nomi di database e tabelle sono case-sensitive
+CREATE DATABASE someDatabase;
+DROP DATABASE someDatabase;
+
+-- Lista dei database disponibili
+SHOW DATABASES;
+
+-- Attiva uno specifico database
+USE employees;
+
+-- Seleziona tutte le righe e le colonne dalla tabella departments
+SELECT * FROM departments;
+
+-- Seleziona tutte le righe della tabella departments,
+-- ma solo le colonne dept_no e dept_name.
+-- È possibile suddividere i comandi su più righe.
+SELECT dept_no,
+ dept_name FROM departments;
+
+-- Seleziona solo le prime 5 righe della tabella departments.
+SELECT * FROM departments LIMIT 5;
+
+-- Ottiene la colonna dept_name della tabella departments
+-- solo per le righe il cui valore di dept_name contiene 'en'.
+SELECT dept_name FROM departments WHERE dept_name LIKE '%en%';
+
+-- Ottiene tutte le colonne della tabella departments
+-- solo per le righe che hanno un dept_name formato da una 'S'
+-- seguita esattamente da altri 4 caratteri
+SELECT * FROM departments WHERE dept_name LIKE 'S____';
+
+-- Seleziona i valori di title dalla tabella titles eliminando i duplicati
+SELECT DISTINCT title FROM titles;
+
+-- Come sopra, ma i valori sono ordinati alfabeticamente
+SELECT DISTINCT title FROM titles ORDER BY title;
+
+-- Mostra il numero di righe della tabella departments
+SELECT COUNT(*) FROM departments;
+
+-- Mostra il numero di righe della tabella departments
+-- il cui valore di dept_name contiene 'en'.
+SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%';
+
+-- Un JOIN tra più tabelle: la tabella titles contiene gli
+-- incarichi lavorativi associati ad un certo numero di impiegato.
+-- Con il JOIN utilizziamo il numero di impiegato per ottenere
+-- le informazioni ad esso associate nella tabella employees.
+-- (Inoltre selezioniamo solo le prime 10 righe)
+
+SELECT employees.first_name, employees.last_name,
+ titles.title, titles.from_date, titles.to_date
+FROM titles INNER JOIN employees ON
+ employees.emp_no = titles.emp_no LIMIT 10;
+
+-- Mostra tutte le tabelle di tutti i database.
+-- Spesso le implementazioni forniscono degli shortcut per questo comando
+SELECT * FROM INFORMATION_SCHEMA.TABLES
+WHERE TABLE_TYPE='BASE TABLE';
+
+-- Crea una tabella tablename1, con due colonne, per il database in uso.
+-- Per le colonne specifichiamo il tipo di dato (stringa di max 20 caratteri)
+CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20));
+
+-- Inserisce una riga nella tabella tablename1. I valori devono essere
+-- appropriati per la definizione della tabella
+INSERT INTO tablename1 VALUES('Richard','Mutt');
+
+-- In tablename1, modifica il valore di fname a 'John'
+-- in tutte le righe che hanno come lname 'Mutt'.
+UPDATE tablename1 SET fname='John' WHERE lname='Mutt';
+
+-- Elimina tutte le righe di tablename1
+-- il cui lname inizia per 'M'.
+DELETE FROM tablename1 WHERE lname like 'M%';
+
+-- Elimina tutte le righe della tabella tablename1
+DELETE FROM tablename1;
+
+-- Elimina la tabella tablename1
+DROP TABLE tablename1;
+```
diff --git a/it-it/zfs-it.html.markdown b/it-it/zfs-it.html.markdown
new file mode 100644
index 00000000..c1307e67
--- /dev/null
+++ b/it-it/zfs-it.html.markdown
@@ -0,0 +1,361 @@
+---
+category: tool
+tool: zfs
+contributors:
+ - ["sarlalian", "http://github.com/sarlalian"]
+translators:
+ - ["Christian Grasso","https://grasso.io"]
+filename: LearnZfs-it.txt
+lang: it-it
+---
+
+
+[ZFS](http://open-zfs.org/wiki/Main_Page) è un sistema di storage che combina file system
+tradizionali e volume manager in un unico strumento. ZFS utilizza della terminologia
+specifica, diversa da quella usata da altri sistemi di storage, ma le sue funzioni lo
+rendono un ottimo tool per gli amministratori di sistema.
+
+
+## Concetti base di ZFS
+
+### Virtual Device
+
+Un VDEV è simile a un dispositivo gestito da una scheda RAID. Esistono diversi tipi di
+VDEV che offrono diversi vantaggi, tra cui ridondanza e velocità. In generale,
+i VDEV offrono una maggiore affidabilità rispetto alle schede RAID. Si sconsiglia di
+utilizzare ZFS insieme a RAID, poichè ZFS è fatto per gestire direttamente i dischi fisici.
+
+Tipi di VDEV:
+
+* stripe (disco singolo, senza ridondanza)
+* mirror (mirror su più dischi)
+* raidz
+ * raidz1 (parity a 1 disco, simile a RAID 5)
+ * raidz2 (parity a 2 dischi, simile a RAID 6)
+ * raidz3 (parity a 3 dischi)
+* disk
+* file (non consigliato in production poichè aggiunge un ulteriore filesystem)
+
+I dati vengono distribuiti tra tutti i VDEV presenti nella Storage Pool, per cui un maggior
+numero di VDEV aumenta le operazioni al secondo (IOPS).
+
+### Storage Pool
+
+Le Storage Pool di ZFS sono un'astrazione del livello inferiore (VDEV) e consentono di
+separare il filesystem visibile agli utenti dal layout reale dei dischi.
+
+### Dataset
+
+I dataset sono simili ai filesystem tradizionali, ma con molte più funzioni che rendono
+vantaggioso l'utilizzo di ZFS. I dataset supportano il [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write)
+gli snapshot, la gestione delle quota, compressione e deduplicazione.
+
+
+### Limiti
+
+Una directory può contenere fino a 2^48 file, ognuno dei quali di 16 exabyte.
+Una storage pool può contenere fino a 256 zettabyte (2^78), e può essere distribuita
+tra 2^64 dispositivi. Un singolo host può avere fino a 2^64 storage pool.
+
+
+## Comandi
+
+### Storage Pool
+
+Azioni:
+
+* List (lista delle pool)
+* Status (stato)
+* Destroy (rimozione)
+* Get/Set (lettura/modifica proprietà)
+
+Lista delle zpool
+
+```bash
+# Crea una zpool raidz
+$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2
+
+# Lista delle zpool
+$ zpool list
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+
+# Informazioni dettagliate su una zpool
+$ zpool list -v zroot
+NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT
+zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE -
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75%
+```
+
+Stato delle zpool
+
+```bash
+# Informazioni sullo stato delle zpool
+$ zpool status
+ pool: zroot
+ state: ONLINE
+ scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+
+# "Scrubbing" (correzione degli errori)
+$ zpool scrub zroot
+$ zpool status -v zroot
+ pool: zroot
+ state: ONLINE
+ scan: scrub in progress since Thu Oct 15 16:59:14 2015
+ 39.1M scanned out of 106G at 1.45M/s, 20h47m to go
+ 0 repaired, 0.04% done
+config:
+
+ NAME STATE READ WRITE CKSUM
+ zroot ONLINE 0 0 0
+ gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0
+
+errors: No known data errors
+```
+
+Proprietà delle zpool
+
+```bash
+
+# Proprietà di una zpool (gestite dal sistema o dall'utente)
+$ zpool get all zroot
+NAME PROPERTY VALUE SOURCE
+zroot size 141G -
+zroot capacity 75% -
+zroot altroot - default
+zroot health ONLINE -
+...
+
+# Modifica di una proprietà
+$ zpool set comment="Dati" zroot
+$ zpool get comment
+NAME PROPERTY VALUE SOURCE
+tank comment - default
+zroot comment Dati local
+```
+
+Rimozione di una zpool
+
+```bash
+$ zpool destroy test
+```
+
+
+### Dataset
+
+Azioni:
+
+* Create
+* List
+* Rename
+* Delete
+* Get/Set (proprietà)
+
+Creazione dataset
+
+```bash
+# Crea un dataset
+$ zfs create tank/root/data
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+
+# Crea un sottodataset
+$ zfs create tank/root/data/stuff
+$ mount | grep data
+tank/root/data on /data (zfs, local, nfsv4acls)
+tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls)
+
+
+# Crea un volume
+$ zfs create -V zroot/win_vm
+$ zfs list zroot/win_vm
+NAME USED AVAIL REFER MOUNTPOINT
+tank/win_vm 4.13G 17.9G 64K -
+```
+
+Lista dei dataset
+
+```bash
+# Lista dei dataset
+$ zfs list
+NAME USED AVAIL REFER MOUNTPOINT
+zroot 106G 30.8G 144K none
+zroot/ROOT 18.5G 30.8G 144K none
+zroot/ROOT/10.1 8K 30.8G 9.63G /
+zroot/ROOT/default 18.5G 30.8G 11.2G /
+zroot/backup 5.23G 30.8G 144K none
+zroot/home 288K 30.8G 144K none
+...
+
+# Informazioni su un dataset
+$ zfs list zroot/home
+NAME USED AVAIL REFER MOUNTPOINT
+zroot/home 288K 30.8G 144K none
+
+# Lista degli snapshot
+$ zfs list -t snapshot
+zroot@daily-2015-10-15 0 - 144K -
+zroot/ROOT@daily-2015-10-15 0 - 144K -
+zroot/ROOT/default@daily-2015-10-15 0 - 24.2G -
+zroot/tmp@daily-2015-10-15 124K - 708M -
+zroot/usr@daily-2015-10-15 0 - 144K -
+zroot/home@daily-2015-10-15 0 - 11.9G -
+zroot/var@daily-2015-10-15 704K - 1.42G -
+zroot/var/log@daily-2015-10-15 192K - 828K -
+zroot/var/tmp@daily-2015-10-15 0 - 152K -
+```
+
+Rinominare un dataset
+
+```bash
+$ zfs rename tank/root/home tank/root/old_home
+$ zfs rename tank/root/new_home tank/root/home
+```
+
+Eliminare un dataset
+
+```bash
+# I dataset non possono essere eliminati se hanno degli snapshot
+$ zfs destroy tank/root/home
+```
+
+Lettura/modifica proprietà
+
+```bash
+# Tutte le proprietà di un dataset
+$ zfs get all zroot/usr/home │157 # Create Volume
+NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm
+zroot/home type filesystem - │159 $ zfs list zroot/win_vm
+zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT
+zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K -
+zroot/home available 94.1G - │162 ```
+zroot/home referenced 11.9G - │163
+zroot/home mounted yes -
+...
+
+# Proprietà specifica
+$ zfs get compression zroot/usr/home
+NAME PROPERTY VALUE SOURCE
+zroot/home compression off default
+
+# Modifica di una proprietà
+$ zfs set compression=gzip-9 mypool/lamb
+
+# Specifiche proprietà per tutti i dataset
+$ zfs list -o name,quota,reservation
+NAME QUOTA RESERV
+zroot none none
+zroot/ROOT none none
+zroot/ROOT/default none none
+zroot/tmp none none
+zroot/usr none none
+zroot/home none none
+zroot/var none none
+...
+```
+
+
+### Snapshot
+
+Gli snapshot sono una delle funzioni più importanti di ZFS:
+
+* Lo spazio occupato è la differenza tra il filesystem e l'ultimo snapshot
+* Il tempo di creazione è di pochi secondi
+* Possono essere ripristinati alla velocità di scrittura del disco
+* Possono essere automatizzati molto semplicemente
+
+Azioni:
+
+* Create
+* Delete
+* Rename
+* Access
+* Send / Receive
+* Clone
+
+
+Creazione di uno snapshot
+
+```bash
+# Crea uno snapshot di un singolo dataset
+zfs snapshot tank/home/sarlalian@now
+
+# Crea uno snapshot di un dataset e dei suoi sottodataset
+$ zfs snapshot -r tank/home@now
+$ zfs list -t snapshot
+NAME USED AVAIL REFER MOUNTPOINT
+tank/home@now 0 - 26K -
+tank/home/sarlalian@now 0 - 259M -
+tank/home/alice@now 0 - 156M -
+tank/home/bob@now 0 - 156M -
+...
+```
+
+Eliminazione di uno snapshot
+
+```bash
+# Elimina uno snapshot
+$ zfs destroy tank/home/sarlalian@now
+
+# Elimina uno snapshot ricorsivamente
+$ zfs destroy -r tank/home/sarlalian@now
+
+```
+
+Rinominare uno snapshot
+
+```bash
+$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today
+$ zfs rename tank/home/sarlalian@now today
+
+$ zfs rename -r tank/home@now @yesterday
+```
+
+Accedere ad uno snapshot
+
+```bash
+# Utilizzare il comando cd come per una directory
+$ cd /home/.zfs/snapshot/
+```
+
+Invio e ricezione
+
+```bash
+# Backup di uno snapshot su un file
+$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz
+
+# Invia uno snapshot ad un altro dataset
+$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian
+
+# Invia uno snapshot ad un host remoto
+$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian'
+
+# Invia l'intero dataset e i suoi snapshot ad un host remoto
+$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home'
+```
+
+Clonare gli snapshot
+
+```bash
+# Clona uno snapshot
+$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new
+
+# Rende il clone indipendente dallo snapshot originale
+$ zfs promote tank/home/sarlalian_new
+```
+
+### Letture aggiuntive (in inglese)
+
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html)
+* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs)
+* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html)
+* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning)
+* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide)
diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown
index c80b4d4c..18e7d1b8 100644
--- a/ja-jp/python-jp.html.markdown
+++ b/ja-jp/python-jp.html.markdown
@@ -160,8 +160,8 @@ len("This is a string") # => 16
name = "Reiko"
f"She said her name is {name}." # => "She said her name is Reiko"
-# 基本的に、任意のPythonの文を中括弧に書くことができ、それは評価されて出力されます。
-f"{name} is {len(name)} characters long."
+# 基本的に、任意のPythonの文を中括弧に書くことができ、それは文字列で出力されます。
+f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long."
# None はオブジェクトです(大文字からです!)
None # => None
@@ -191,7 +191,7 @@ print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!
print("Hello, World", end="!") # => Hello, World!
# コンソールから入力を得るための簡単な例
-input_string_var = input("Enter some data: ") # 入力を文字列として返します
+input_string_var = input("Enter some data: ") # 入力を文字列として返します。
# Note: Python の初期のバージョンでは、 input() は raw_input() という名前で存在します。
# Pythonでは変数の宣言は存在せず、代入のみです。
@@ -201,7 +201,7 @@ some_var # => 5
# 代入されていない変数へのアクセスは例外を引き起こします。
# 例外の取り扱いについては、3章の制御の流れをご確認ください。
-some_unknown_var # NameError を送出します
+some_unknown_var # NameError を送出します。
# ifは式として使用できます。
# C言語の「?:(三項演算子)」に対応する例:
@@ -228,7 +228,7 @@ li[0] # => 1
li[-1] # => 3
# 範囲外の要素を参照すると IndexError になります。
-li[4] # IndexError が発生します
+li[4] # IndexError が発生します。
# スライス構文により範囲を参照できます。
# 開始部分のインデックスに対応する部分は含まれますが、終了部分のインデックスに対応する部分は含まれません。
@@ -238,28 +238,28 @@ li[2:] # => [4, 3]
# 末尾を取り除いたリスト
li[:3] # => [1, 2, 4]
# 1つ飛ばしで選択する
-li[::2] # =>[1, 4]
+li[::2] # => [1, 4]
# 反転したリストを得る
li[::-1] # => [3, 4, 2, 1]
# これらの任意の組み合わせにより、より複雑なスライスを作ることができます。
# li[start:end:step]
# スライスにより、深いコピーを1階層分行うことができます。
-li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) はFalseになる。
+li2 = li[:] # => li2 = [1, 2, 4, 3] だが、 (li2 is li) は False になる。
# "del"によりリストから任意の要素を削除できます。
del li[2] # li は [1, 2, 3] になりました。
# "remove"で最初に出現する要素を削除できます。
li.remove(2) # li は [1, 3] になりました。
-li.remove(2) # 2はリストの中に存在しないので、 ValueError が発生します。
+li.remove(2) # 2 はリストの中に存在しないので、 ValueError が発生します。
# 要素を好きなところに挿入できます。
li.insert(1, 2) # li は [1, 2, 3] に戻りました。
# "index"で引数の要素が最初に出現する場所のインデックスを得られます。
li.index(2) # => 1
-li.index(4) # 4はリストの中に存在しないので、 ValueError が発生します。
+li.index(4) # 4 はリストの中に存在しないので、 ValueError が発生します。
# リスト同士を足すこともできます。
# Note: li と other_li の値は変更されません。
@@ -295,11 +295,11 @@ tup[:2] # => (1, 2)
# タプルやリストから複数の変数に代入することができます。
a, b, c = (1, 2, 3) # a, b, c にはそれぞれ 1, 2, 3 が代入されました。
# 拡張記法もあります。
-a, *b, c = (1, 2, 3, 4) # a は 1 、 b は [2, 3] 、c は4 になります。
+a, *b, c = (1, 2, 3, 4) # a は 1、 b は [2, 3]、c は 4 になります。
# 括弧を作成しなくてもデフォルトでタプルが作成されます。
d, e, f = 4, 5, 6 # 4、5、6がそれぞれd、 e、 fに代入されます。
# 2つの変数を交換するのがどれほど簡単か見てみましょう。
-e, d = d, e # d は 5 、 e は e になります。
+e, d = d, e # d は 5、 e は 4 になります。
# 辞書はマップ(キーと値の組み合わせ)を保存できます。
@@ -373,7 +373,7 @@ valid_set = {(1,), 1}
filled_set = some_set
filled_set.add(5) # filled_set は {1, 2, 3, 4, 5} になりました。
# 集合は重複した要素を持ちません。
-filled_set.add(5) # 以前の{1, 2, 3, 4, 5}のままです。
+filled_set.add(5) # 以前の {1, 2, 3, 4, 5} のままです。
# & により、集合同士の共通部分が得られます。
other_set = {3, 4, 5, 6}
@@ -453,7 +453,7 @@ for i in range(4, 8):
"""
"range(lower, upper, step)" は、lower の数値から upper の数値までが、
-step 刻みで表現されるiterableを返します
+step 刻みで表現されるiterableを返します。
step が与えられない場合、デフォルトは1になります。
出力:
4
@@ -552,7 +552,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
def keyword_args(**kwargs):
return kwargs
-# 何が起こるか、試してみましょう
+# 何が起こるか、試してみましょう。
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
@@ -591,7 +591,7 @@ x = 5
def set_x(num):
- # ローカル変数の x はグローバル変数の x とは異なります
+ # ローカル変数の x はグローバル変数の x とは異なります。
x = num # => 43
print(x) # => 43
@@ -783,7 +783,7 @@ if __name__ == '__main__':
from human import Human
-# 親クラスを子クラスのパラメータとして指定します
+# 親クラスを子クラスのパラメータとして指定します。
class Superhero(Human):
# もし子クラスが親クラスの全ての定義を変更なしで継承する場合、"pass"キーワードのみを書くだけで良いです。
diff --git a/jsonnet.html.markdown b/jsonnet.html.markdown
new file mode 100644
index 00000000..175642d4
--- /dev/null
+++ b/jsonnet.html.markdown
@@ -0,0 +1,139 @@
+---
+language: jsonnet
+filename: learnjsonnet.jsonnet
+contributors:
+ - ["Huan Wang", "https://github.com/fredwangwang"]
+---
+
+Jsonnet is a powerful templating language for JSON. Any valid JSON
+document is a valid Jsonnet object. For an interactive demo/tutorial,
+click [here](https://jsonnet.org/learning/tutorial.html)
+
+```python
+// single line comment
+
+/*
+ multiline comment
+*/
+
+// as well as python style comment
+
+# define a variable.
+# Variables have no effect in the generated JSON without being used.
+local num1 = 1;
+local num2 = 1 + 1;
+local num3 = 5 - 2;
+local num4 = 9 % 5;
+local num5 = 10 / 2.0;
+# jsonnet is a lazy language, if a variable is not used, it is not evaluated.
+local num_runtime_error = 1 / 0;
+
+# fields are valid identifiers without quotes
+local obj1 = { a: 'letter a', B: 'letter B' };
+
+local arr1 = ['a', 'b', 'c'];
+
+# string literals use " or '.
+local str1 = 'a' + 'B';
+# multiline text literal in between |||
+# Each line must start with a white space.
+local str_multiline = |||
+ this is a
+ multiline string
+|||;
+# Python-compatible string formatting is available via %
+# When combined with ||| this can be used for templating text files.
+local str_templating = |||
+ %(f1)0.3f
+||| % { f1: 1.2345678 };
+assert str_templating == '1.235\n';
+
+# if b then e else e. The else branch is optional and defaults to null
+local var1 = if 3 < 2 then "YES";
+assert var1 == null;
+
+local obj2 = {
+ # variable defined inside the object ends with ','
+ local var_in_obj = 0,
+
+ local vowels = ['a', 'e', 'i', 'o', 'u'],
+ local numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
+
+ # [num] to look up an array element
+ first_vowel: vowels[0],
+ # can also slice the array like in Python
+ even_numbers: numbers[1::2],
+
+ # python-style list and object comprehensions are also supported
+ double_numbers: [x * 2 for x in numbers],
+ even_numbers_map: {
+ # [ ] syntax in field name is to compute the field name dynamically
+ [x + '_is_even']: true for x in numbers if x % 2 == 0
+ },
+
+ nested: {
+ nested_field1: 'some-value',
+ # self refers to the current object
+ # ["field-name"] or .field-name can be used to look up a field
+ nested_field2: self.nested_field1,
+ nested_field3: self.nested_field1,
+ # $ refers to outer-most object
+ nested_field4: $.first_vowel,
+
+ assert self.nested_field1 == self.nested_field2,
+ assert self.nested_field1 == self.nested_field3,
+ },
+
+ special_field: 'EVERYTHING FEELS BAD',
+};
+
+local obj3 = {
+ local var_in_obj = 1.234,
+ local var_in_obj2 = { a: { b: 'c' } },
+
+ concat_array: [1, 2, 3] + [4],
+ # strings can be concat with +,
+ # which implicitly converts one operand to string if needed.
+ concat_string: '123' + 4,
+
+ # == tests deep equality
+ equals: { a: { b: 'c', d: {} } } == var_in_obj2,
+
+ special_field: 'this feels good',
+};
+
+# objects can be merged with + where the right-hand side wins field conflicts
+local obj4 = obj2 + obj3;
+assert obj4.special_field == 'this feels good';
+
+# define a function
+# functions have positional parameters, named parameters, and default arguments
+local my_function(x, y, z=1) = x + y - z;
+local num6 = my_function(7, 8, 9);
+local num7 = my_function(8, z=10, y=9);
+local num8 = my_function(4, 5);
+# inline anonymous function
+local num9 = (function(x) x * x)(3);
+
+local obj5 = {
+ # define a method
+ # fields defined with :: are hidden, which does not apper in generated JSON
+ # function cannot be serialized so need to be hidden
+ # if the object is used in the generated JSON.
+ is_odd(x):: x % 2 == 1,
+};
+assert obj5 == {};
+
+# a jsonnet doucment have to evaluate to something
+# be it an object, list, number or just string literal
+"FIN"
+
+```
+
+## Further Reading
+There are a few but important concepts that are not touched in this exmaple, including:
+
+- Passing variables from command line: [Parameterize Entire Config](https://jsonnet.org/learning/tutorial.html#parameterize-entire-config)
+- Import other jsonnet libraries/files: [Imports](https://jsonnet.org/learning/tutorial.html#imports)
+- In depth example of OOP aspect of Jsonnet: [Object-Orientation](https://jsonnet.org/learning/tutorial.html#Object-Orientation)
+- Useful standard library: [Stdlib](https://jsonnet.org/ref/stdlib.html)
diff --git a/ko-kr/vim-kr.html.markdown b/ko-kr/vim-kr.html.markdown
index cd0fa236..76063143 100644
--- a/ko-kr/vim-kr.html.markdown
+++ b/ko-kr/vim-kr.html.markdown
@@ -5,12 +5,13 @@ contributors:
- ["RadhikaG", "https://github.com/RadhikaG"]
translators:
- ["Wooseop Kim", "https://github.com/linterpreteur"]
+ - ["Yeongjae Jang", "https://github.com/Liberatedwinner"]
filename: LearnVim-kr.txt
lang: ko-kr
---
[Vim](http://www.vim.org)
-(Vi IMproved)은 유닉스의 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해
+(Vi IMproved)은 유닉스에서 인기 있는 vi 에디터의 클론입니다. Vim은 속도와 생산성을 위해
설계된 텍스트 에디터로, 대부분의 유닉스 기반 시스템에 내장되어 있습니다. 다양한 단축 키를 통해
파일 안에서 빠르게 이동하고 편집할 수 있습니다.
@@ -18,19 +19,21 @@ lang: ko-kr
```
vim <filename> # vim으로 <filename> 열기
+ :help <topic> # (존재하는 경우에) <topic>에 대한, 내장된 도움말 문서 열기
:q # vim 종료
:w # 현재 파일 저장
:wq # 파일 저장 후 종료
+ ZZ # 파일 저장 후 종료
:q! # 저장하지 않고 종료
# ! *강제로* :q를 실행하여, 저장 없이 종료
- :x # 파일 저장 후 종료 (짧은 :wq)
+ :x # 파일 저장 후 종료 (:wq의 축약)
u # 동작 취소
CTRL+R # 되돌리기
h # 한 글자 왼쪽으로 이동
- j # 아래로 한 줄 이동
- k # 위로 한 줄 이동
+ j # 한 줄 아래로 이동
+ k # 한 줄 위로 이동
l # 한 글자 오른쪽으로 이동
# 줄 안에서의 이동
@@ -38,6 +41,11 @@ lang: ko-kr
0 # 줄 시작으로 이동
$ # 줄 끝으로 이동
^ # 줄의 공백이 아닌 첫 문자로 이동
+
+ Ctrl+B # 한 화면 뒤로 이동
+ Ctrl+F # 한 화면 앞으로 이동
+ Ctrl+D # 반 화면 앞으로 이동
+ Ctrl+U # 반 화면 뒤로 이동
# 텍스트 검색
@@ -48,6 +56,8 @@ lang: ko-kr
:%s/foo/bar/g # 파일 모든 줄에 있는 'foo'를 'bar'로 치환
:s/foo/bar/g # 현재 줄에 있는 'foo'를 'bar'로 치환
+ :%s/foo/bar/gc # 사용자에게 확인을 요구하는, 모든 줄에 있는 'foo'를 'bar'로 치환
+ :%s/\n/\r/g # 한 종류의 개행 문자에서 다른 종류의 것으로 치환 (\n에서 \r로)
# 문자로 이동
@@ -74,14 +84,22 @@ lang: ko-kr
L # 화면 바닥으로 이동
```
+## 도움말 문서
+
+Vim은 `:help <topic>` 명령을 통해 접근할 수 있는 도움말 문서를 내장하고 있습니다.
+예를 들어, `:help navigation` 은 당신의 작업 공간을 탐색하는 방법에 대한 문서를 표시합니다!
+
+`:help`는 옵션 없이도 사용할 수 있습니다. 이는 기본 도움말 대화 상자를 표시합니다.
+이 대화 상자는 Vim을 시작하는 것이 보다 용이하도록 도와줍니다.
+
## 모드
Vim은 **모드**의 개념에 기초를 두고 있습니다.
-명령어 모드 - vim을 시작하면 처음에 이 모드입니다. 이동과 명령어 입력에 사용합니다.
-삽입 모드 - 파일을 수정합니다.
-비주얼 모드 - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다.
-실행 모드 - ':' 이후 명령어를 입력합니다.
+- 명령어 모드 - vim은 이 모드로 시작됩니다. 이동과 명령어 입력에 사용합니다.
+- 삽입 모드 - 파일을 수정합니다.
+- 비주얼 모드 - 텍스트를 하이라이트하고 그 텍스트에 대한 작업을 합니다.
+- 실행 모드 - ':' 이후 명령어를 입력합니다.
```
i # 커서 위치 앞에서 삽입 모드로 변경
@@ -97,11 +115,11 @@ Vim은 **모드**의 개념에 기초를 두고 있습니다.
d # 선택한 객체 삭제
dd # 현재 줄 삭제
p # 커서 위치 뒤에 복사한 텍스트 붙여넣기
- P # 커서 위치 뒤에 복사한 텍스트 붙여넣기
+ P # 커서 위치 앞에 복사한 텍스트 붙여넣기
x # 현재 커서 위치의 문자 삭제
```
-## vim의 문법
+## vim의 '문법'
Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니다.
@@ -134,7 +152,7 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니
w # 단어를
s # 문장을
p # 문단을
- b # 블락을
+ b # 블록을
# 예시 '문장' (명령어)
@@ -157,6 +175,22 @@ Vim의 명령어는 '서술어-수식어-목적어'로 생각할 수 있습니
ddp # 이어지는 줄과 위치 맞바꾸기 (dd 후 p)
. # 이전 동작 반복
:w !sudo tee % # 현재 파일을 루트 권한으로 저장
+ :set syntax=c # 문법 강조를 'C'의 것으로 설정
+ :sort # 모든 줄을 정렬
+ :sort! # 모든 줄을 역순으로 정렬
+ :sort u # 모든 줄을 정렬하고, 중복되는 것을 삭제
+ ~ # 선택된 텍스트의 대/소문자 토글
+ u # 선택된 텍스트를 소문자로 바꾸기
+ U # 선택된 텍스트를 대문자로 바꾸기
+
+ # 텍스트 폴딩
+ zf # 선택된 텍스트 위치에서 폴딩 만들기
+ zo # 현재 폴딩 펴기
+ zc # 현재 폴딩 접기
+ zR # 모든 폴딩 펴기
+ zM # 모든 폴딩 접기
+ zi # 폴딩 접기/펴기 토글
+ zd # 접은 폴딩 삭제
```
## 매크로
diff --git a/ldpl.html.markdown b/ldpl.html.markdown
index cc95f5fb..86603d94 100644
--- a/ldpl.html.markdown
+++ b/ldpl.html.markdown
@@ -165,19 +165,6 @@ display myNumber crlf
exit
```
-## Topics Not Covered
-
- * [Command line arguments](https://docs.ldpl-lang.org/variables-in-ldpl/command-line-arguments)
- * [Error variables](https://docs.ldpl-lang.org/variables-in-ldpl/errorcode-and-errortext)
- * [Import other files](https://docs.ldpl-lang.org/structure-of-ldpl-source-code/importing-other-sources)
- * [Identifier naming schemes](https://docs.ldpl-lang.org/naming-rules)
- * [Text Statements](https://docs.ldpl-lang.org/text-statements/join-and-in)
- * [List Statements](https://docs.ldpl-lang.org/list-statements/push-to)
- * [Map Statements](https://docs.ldpl-lang.org/vector-statements/clear)
- * [File loading / writing](https://docs.ldpl-lang.org/i-o-statements/load-file-in)
- * [Executing commands](https://docs.ldpl-lang.org/i-o-statements/execute)
- * [Extending LDPL with C++](https://docs.ldpl-lang.org/extensions/c++-extensions)
-
## Further Reading
* [LDPL Docs](https://docs.ldpl-lang.org)
diff --git a/lua.html.markdown b/lua.html.markdown
index 0a7c4f00..53e396be 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -116,7 +116,7 @@ function bar(a, b, c)
end
x, y = bar('zaphod') --> prints "zaphod nil nil"
--- Now x = 4, y = 8, values 15..42 are discarded.
+-- Now x = 4, y = 8, values 15...42 are discarded.
-- Functions are first-class, may be local/global.
-- These are the same:
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 5790bcc6..4ca31857 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -234,7 +234,7 @@ A' % Concise version of complex transpose
% On their own, the arithmetic operators act on whole matrices. When preceded
% by a period, they act on each element instead. For example:
A * B % Matrix multiplication
-A .* B % Multiple each element in A by its corresponding element in B
+A .* B % Multiply each element in A by its corresponding element in B
% There are several pairs of functions, where one acts on each element, and
% the other (whose name ends in m) acts on the whole matrix.
diff --git a/mips.html.markdown b/mips.html.markdown
index 7f759bec..33d4f87c 100644
--- a/mips.html.markdown
+++ b/mips.html.markdown
@@ -209,7 +209,7 @@ gateways and routers.
## LOOPS ##
_loops:
# The basic structure of loops is having an exit condition and a jump
- instruction to continue its execution
+ # instruction to continue its execution
li $t0, 0
while:
bgt $t0, 10, end_while # While $t0 is less than 10,
diff --git a/moonscript.html.markdown b/moonscript.html.markdown
index 941578e7..193d7f97 100644
--- a/moonscript.html.markdown
+++ b/moonscript.html.markdown
@@ -192,7 +192,7 @@ items = {1, 2, 3, 4}
doubled = [item * 2 for item in *items]
-- Uses `when` to determine if a value should be included.
-slice = [item for item in *items when i > 1 and i < 3]
+slice = [item for item in *items when item > 1 and item < 3]
-- `for` clauses inside of list comprehensions can be chained.
diff --git a/nix.html.markdown b/nix.html.markdown
index 5941f0e6..dde5dbec 100644
--- a/nix.html.markdown
+++ b/nix.html.markdown
@@ -279,7 +279,7 @@ with builtins; [
#=> 7
# This first line of tutorial starts with "with builtins;"
- # because builtins is a set the contains all of the built-in
+ # because builtins is a set that contains all of the built-in
# functions (length, head, tail, filter, etc.). This saves
# us from having to write, for example, "builtins.length"
# instead of just "length".
diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown
index 906112ff..d243802d 100644
--- a/nl-nl/json-nl.html.markdown
+++ b/nl-nl/json-nl.html.markdown
@@ -5,26 +5,27 @@ contributors:
- ["Anna Harren", "https://github.com/iirelu"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
- ["himanshu", "https://github.com/himanshu81494"]
+ - ["Maarten Jacobs", "https://github.com/maartenJacobs"]
translators:
- ["Niels van Velzen", "https://nielsvanvelzen.me"]
lang: nl-nl
---
-Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste
+Gezien JSON een zeer eenvouding formaat heeft zal dit één van de simpelste
Learn X in Y Minutes ooit zijn.
-JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de
+JSON heeft volgens de specificaties geen commentaar. Ondanks dat hebben de
meeste parsers support voor C-stijl (`//`, `/* */`) commentaar.
Sommige parsers staan zelfs trailing komma's toe.
-(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object).
-Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken.
+(Een komma na het laatste element in een array of achter de laatste eigenschap van een object).
+Het is wel beter om dit soort dingen te vermijden omdat het niet in elke parser zal werken.
In het voorbeeld zal alleen 100% geldige JSON gebruikt worden.
Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null.
Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4.
-De extensie voor JSON bestanden is ".json". De MIME type is "application/json"
-Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD.
+De extensie voor JSON bestanden is ".json". De MIME type is "application/json".
+Enkele nadelen van JSON zijn het gebrek aan type definities en een manier van DTD.
```json
{
diff --git a/p5.html.markdown b/p5.html.markdown
index be22d3e5..f6084b98 100644
--- a/p5.html.markdown
+++ b/p5.html.markdown
@@ -7,7 +7,7 @@ contributors:
filename: p5.js
---
-p5.js is a JavaScript library that starts with the original goal of [Processing](http://processing.org"), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.
+p5.js is a JavaScript library that starts with the original goal of [Processing](https://processing.org), to make coding accessible for artists, designers, educators, and beginners, and reinterprets this for today's web.
Since p5 is a JavaScript library, you should learn [Javascript](https://learnxinyminutes.com/docs/javascript/) first.
```js
diff --git a/perl.html.markdown b/perl.html.markdown
index 08001ab0..8811dd08 100644
--- a/perl.html.markdown
+++ b/perl.html.markdown
@@ -8,9 +8,9 @@ contributors:
- ["Dan Book", "http://github.com/Grinnz"]
---
-Perl 5 is a highly capable, feature-rich programming language with over 25 years of development.
+Perl is a highly capable, feature-rich programming language with over 25 years of development.
-Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
+Perl runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects.
```perl
# Single line comments start with a number sign.
diff --git a/php.html.markdown b/php.html.markdown
index d4103e97..57ba29c4 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -34,6 +34,7 @@ echo "World\n"; // Prints "World" with a line break
?>
Hello World Again!
<?php
+// That is because historically PHP started as a Template engine
/************************************
@@ -41,12 +42,15 @@ Hello World Again!
*/
// Variables begin with the $ symbol.
-// A valid variable name starts with a letter or underscore,
+// A valid variable name starts with a letter or an underscore,
// followed by any number of letters, numbers, or underscores.
+// You don't have to (and cannot) declare variables.
+// Once you assign a value, PHP will create the variable with the right type.
+
// Boolean values are case-insensitive
$boolean = true; // or TRUE or True
-$boolean = false; // or FALSE or False
+$boolean = FALSE; // or false or False
// Integers
$int1 = 12; // => 12
diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown
index 3e27cc4f..43d68b05 100644
--- a/pl-pl/perl-pl.html.markdown
+++ b/pl-pl/perl-pl.html.markdown
@@ -12,10 +12,10 @@ lang: pl-pl
---
-Perl 5 jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
+Perl jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
z ponad 25 latami nieustannego rozwoju.
-Perl 5 używany jest na ponad 100 różnych platformach (od przenośnych do w
+Perl używany jest na ponad 100 różnych platformach (od przenośnych do w
pełni stacjonarnych) i nadaje się zarówno do szybkiego prototypowania jak
i projektów deweloperskich prowadzonych na szeroką skalę.
diff --git a/powershell.html.markdown b/powershell.html.markdown
index 5d74024d..6efd984c 100644
--- a/powershell.html.markdown
+++ b/powershell.html.markdown
@@ -55,6 +55,11 @@ The tutorial starts here:
```powershell
# As you already figured, comments start with #
+<#
+ Multi-line comments
+ like so
+#>
+
# Simple hello world example:
echo Hello world!
# echo is an alias for Write-Output (=cmdlet)
@@ -68,6 +73,8 @@ $aString="Some string"
# Or like this:
$aNumber = 5 -as [double]
$aList = 1,2,3,4,5
+# Reverse an array *Note this is a mutation on the existing array
+[array]::Reverse($aList)
$anEmptyList = @()
$aString = $aList -join '--' # yes, -split exists also
$aHashtable = @{name1='val1'; name2='val2'}
@@ -100,6 +107,10 @@ echo "Bound arguments in a function, script or code block: $PSBoundParameters"
echo "Unbound arguments: $($Args -join ', ')."
# More builtins: `help about_Automatic_Variables`
+# Find the datatype of variables or properties you're working with
+$true.GetType()
+$aHashtable.name2.GetType()
+
# Inline another file (dot operator)
. .\otherScriptName.ps1
@@ -184,7 +195,7 @@ Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM `
Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List
# Use % as a shorthand for ForEach-Object
-(a,b,c) | ForEach-Object `
+('a','b','c') | ForEach-Object `
-Begin { "Starting"; $counter = 0 } `
-Process { "Processing $_"; $counter++ } `
-End { "Finishing: $counter" }
@@ -198,12 +209,13 @@ ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize
### Functions
# The [string] attribute is optional.
-function foo([string]$name) {
+# Function names should follow Verb-Noun convention
+function Get-Foo([string]$name) {
echo "Hey $name, have a function"
}
# Calling your function
-foo "Say my name"
+Get-Foo "Say my name"
# Functions with named parameters, parameter attributes, parsable documentation
<#
@@ -283,7 +295,22 @@ Pop-Location # change back to previous working directory
# Unblock a directory after download
Get-ChildItem -Recurse | Unblock-File
+# You can also pass arguments to a Function with a hash table
+# This is called Splatting
+# Normal Command
+Export-Csv -InputObject $csv -Path 'c:\mypath' -Encoding UTF8 -NoTypeInformation
+# With Splatting
+$csvArguments = @{
+ InputObject = $csv
+ Path = 'c:\mypath'
+ Encoding = 'UTF8'
+ NoTypeInformation = $true
+}
+Export-Csv @csvArguments
+
# Open Windows Explorer in working directory
+Invoke-Item .
+# Or the alias
ii .
# Any key to exit
@@ -318,6 +345,7 @@ Interesting Projects
* [PSGet](https://github.com/psget/psget) NuGet for PowerShell
* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!)
* [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!)
+* [Oh-My-Posh](https://github.com/JanDeDobbeleer/oh-my-posh) Shell customization similar to the popular Oh-My-Zsh on Mac
* [PSake](https://github.com/psake/psake) Build automation tool
* [Pester](https://github.com/pester/Pester) BDD Testing Framework
* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind
diff --git a/processing.html.markdown b/processing.html.markdown
index d99912e7..777c6981 100644
--- a/processing.html.markdown
+++ b/processing.html.markdown
@@ -150,7 +150,7 @@ SomeRandomClass myObjectInstantiated = new SomeRandomClass();
// operations.
float f = sq(3); // f = 9.0
float p = pow(3, 3); // p = 27.0
-int a = abs(-13) // a = 13
+int a = abs(-13); // a = 13
int r1 = round(3.1); // r1 = 3
int r2 = round(3.7); // r2 = 4
float sr = sqrt(25); // sr = 5.0
@@ -191,6 +191,8 @@ int i = 3;
String value = (i > 5) ? "Big" : "Small"; // "Small"
// Switch-case structure can be used to check multiple conditions concisely.
+// It is important to use the break statement. If the `break`-statement does
+// not exist the program executes all the following cases after a case was true.
int value = 2;
switch(value) {
case 0:
@@ -209,7 +211,7 @@ switch(value) {
// Iterative statements
// For Statements - Again, the same syntax as in Java
-for(int i = 0; i < 5; i ++){
+for(int i = 0; i < 5; i++){
print(i); // prints from 0 to 4
}
@@ -354,14 +356,14 @@ color c = color(255, 255, 255); // WHITE!
// By default, Processing uses RGB colour scheme but it can be configured to
// HSB using colorMode(). Read more here:
// (https://processing.org/reference/colorMode_.html)
-background(color); // By now, the background colour should be white.
+background(c); // By now, the background colour should be white.
// You can use fill() function to select the colour for filling the shapes.
// It has to be configured before you start drawing shapes so the colours gets
// applied.
fill(color(0, 0, 0));
// If you just want to colour the outlines of the shapes then you can use
// stroke() function.
-stroke(255, 255, 255, 200); // stroke colour set to yellow with transparency
+stroke(255, 255, 0, 200); // stroke colour set to yellow with transparency
// set to a lower value.
// Images
diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown
index 217861f9..55a10626 100644
--- a/pt-br/perl-pt.html.markdown
+++ b/pt-br/perl-pt.html.markdown
@@ -10,9 +10,9 @@ translators:
lang: pt-br
---
-Perl 5 é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento.
+Perl é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento.
-Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala.
+Perl roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala.
```perl
# Comentários de uma linha começam com um sinal de número.
diff --git a/python.html.markdown b/python.html.markdown
index 56cb9aac..44ed7ed9 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -132,7 +132,7 @@ b == a # => True, a's and b's objects are equal
"Hello " "world!" # => "Hello world!"
# A string can be treated like a list of characters
-"This is a string"[0] # => 'T'
+"Hello world!"[0] # => 'H'
# You can find the length of a string
len("This is a string") # => 16
@@ -772,11 +772,11 @@ if __name__ == '__main__':
# Call the static method
print(Human.grunt()) # => "*grunt*"
-
- # Cannot call static method with instance of object
+
+ # Cannot call static method with instance of object
# because i.grunt() will automatically put "self" (the object i) as an argument
print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given
-
+
# Update the property for this instance
i.age = 42
# Get the property
@@ -792,7 +792,7 @@ if __name__ == '__main__':
####################################################
# Inheritance allows new child classes to be defined that inherit methods and
-# variables from their parent class.
+# variables from their parent class.
# Using the Human class defined above as the base or parent class, we can
# define a child class, Superhero, which inherits the class variables like
@@ -926,7 +926,7 @@ class Batman(Superhero, Bat):
# So instead we explicitly call __init__ for all ancestors.
# The use of *args and **kwargs allows for a clean way to pass arguments,
# with each parent "peeling a layer of the onion".
- Superhero.__init__(self, 'anonymous', movie=True,
+ Superhero.__init__(self, 'anonymous', movie=True,
superpowers=['Wealthy'], *args, **kwargs)
Bat.__init__(self, *args, can_fly=False, **kwargs)
# override the value for the name attribute
@@ -941,9 +941,9 @@ if __name__ == '__main__':
# Get the Method Resolution search Order used by both getattr() and super().
# This attribute is dynamic and can be updated
- print(Batman.__mro__) # => (<class '__main__.Batman'>,
- # => <class 'superhero.Superhero'>,
- # => <class 'human.Human'>,
+ print(Batman.__mro__) # => (<class '__main__.Batman'>,
+ # => <class 'superhero.Superhero'>,
+ # => <class 'human.Human'>,
# => <class 'bat.Bat'>, <class 'object'>)
# Calls parent method but uses its own class attribute
@@ -1040,3 +1040,5 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/)
* [Dive Into Python 3](http://www.diveintopython3.net/index.html)
* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718)
+* [Python Tutorial for Intermediates](https://pythonbasics.org/)
+* [Build a Desktop App with Python](https://pythonpyqt.com/)
diff --git a/perl6-pod.html.markdown b/raku-pod.html.markdown
index 80a501b8..7e9b6fc3 100644
--- a/perl6-pod.html.markdown
+++ b/raku-pod.html.markdown
@@ -5,9 +5,9 @@ contributors:
filename: learnpod.pod6
---
-Pod is an easy-to-use and purely descriptive mark-up language,
+Pod is an easy-to-use and purely descriptive mark-up language,
with no presentational components. Besides its use for documenting
-Raku Perl 6 programs and modules, Pod can be utilized to write language
+Raku programs and modules, Pod can be utilized to write language
documentation, blogs, and other types of document composition as well.
Pod documents can be easily converted to HTML and many other formats
@@ -49,12 +49,12 @@ generate documentation.
```
=begin pod
-A very simple Raku Perl 6 Pod document. All the other directives go here!
+A very simple Raku Pod document. All the other directives go here!
=end pod
```
-Pod documents usually coexist with Raku Perl 6 code. If by themselves,
+Pod documents usually coexist with Raku code. If by themselves,
Pod files often have the `.pod6` suffix. Moving forward, it's assumed that
the constructs being discussed are surrounded by the `=begin pod ... =end pod`
directives.
@@ -65,7 +65,7 @@ directives.
Text can be easily styled as bold, italic, underlined or verbatim (for code
formatting) using the following formatting codes: `B<>`, `I<>`, `U<>`
-and `C<>`.
+and `C<>`.
```
B<This text is in Bold.>
@@ -83,7 +83,7 @@ just a single capital letter followed immediately by a set of single or double
angle brackets. The Unicode variant («») of the angle brackets can also be
used.
-### Headings
+### Headings
Headings are created by using the `=headN` directive where `N` is the
heading level.
@@ -145,7 +145,7 @@ Unordered lists can be created using the `=item` directive.
```
Sublists are achieved with items at each level specified using the `=item1`,
-`=item2`, `=item3`, `...`, `=itemN` etc. directives. The `=item` directive
+`=item2`, `=item3`, `...`, `=itemN` etc. directives. The `=item` directive
defaults to `=item1`.
```
@@ -157,7 +157,7 @@ defaults to `=item1`.
=item1 Item four
```
-Definition lists that define terms or commands use the `=defn` directive.
+Definition lists that define terms or commands use the `=defn` directive.
This is equivalent to the `<dl>` element in HTML.
```
@@ -186,13 +186,13 @@ As shown in the [Basic Text Formatting](#basic-text-formatting) section,
inline code can be created using the `C<>` code.
```
-In Raku Perl 6, there are several functions/methods to output text. Some of them
+In Raku, there are several functions/methods to output text. Some of them
are C<print>, C<put> and C<say>.
```
### Comments
-Although Pod blocks are ignored by the Raku Perl 6 compiler, everything
+Although Pod blocks are ignored by the Rakudo Raku compiler, everything
indentified as a Pod block will be read and interpreted by Pod renderers. In
order to prevent Pod blocks from being rendered by any renderer, use the
`=comment` directive.
@@ -206,21 +206,21 @@ order to prevent Pod blocks from being rendered by any renderer, use the
To create inline comments, use the `Z<>` code.
```
-Pod is awesome Z<Of course it is!>. And Raku Perl 6 too!
+Pod is awesome Z<Of course it is!>. And Raku too!
```
-Given that the Perl interpreter never executes embedded Pod blocks,
+Given that the Raku interpreter never executes embedded Pod blocks,
comment blocks can also be used as an alternative form of nestable block
-comments in Raku Perl 6.
+comments.
### Links
Creating links in Pod is quite easy and is done by enclosing them in
a `L<>` code. The general format is `L<Label|Url>` with `Label`
-being optional.
+being optional.
```
-Raku Perl 6 homepage is L<https://perl6.org>.
+Raku homepage is L<https://raku.org>.
L<Click me!|http://link.org/>.
```
@@ -242,7 +242,7 @@ The Pod specifications are not completely handled properly yet and this
includes the handling of table. For simplicity's sake, only one way of
constructing tables is shown here. To learn about good practices and see
examples of both good and bad tables, please visit
-<https://docs.perl6.org/language/tables>.
+<https://docs.raku.org/language/tables>.
```
=begin table
@@ -287,7 +287,7 @@ For example:
Delimited blocks are bounded by `=begin` and `=end` markers, both of which are
followed by a valid Pod identifier, which is the `typename` of the block.
-The general syntax is
+The general syntax is
```
=begin BLOCK_TYPE
@@ -304,7 +304,7 @@ Top level heading
```
This type of blocks is useful for creating headings, list items, code blocks,
-etc. with multiple paragraphs. For example,
+etc. with multiple paragraphs. For example,
* a multiline item of a list
@@ -345,7 +345,7 @@ say pow(6); #=> 36
Paragraph blocks are introduced by a `=for` marker and terminated by
the next Pod directive or the first blank line (which is not considered to
be part of the block's contents). The `=for` marker is followed by the
-`typename` of the block. The general syntax is
+`typename` of the block. The general syntax is
```
=for BLOCK_TYPE
@@ -360,10 +360,10 @@ Top level heading
```
## Configuration Data
-
+
Except for abbreviated blocks, both delimited blocks and paragraph
blocks can be supplied with configuration information about their
-contents right after the `typename` of the block. Thus the following
+contents right after the `typename` of the block. Thus the following
are more general syntaxes for these blocks:
* Delimited blocks
@@ -384,16 +384,16 @@ BLOCK DATA
```
The configuration information is provided in a format akin to the
-["colon pair"](https://docs.perl6.org/language/glossary#index-entry-Colon_Pair)
-syntax in Raku Perl 6. The following table is a simplified version of the
-different ways in which configuration info can be supplied. Please go to
-<https://docs.perl6.org/language/pod#Configuration_information> for a more
+["colon pair"](https://docs.raku.org/language/glossary#index-entry-Colon_Pair)
+syntax in Raku. The following table is a simplified version of the
+different ways in which configuration info can be supplied. Please go to
+<https://docs.raku.org/language/pod#Configuration_information> for a more
thorough treatment of the subject.
| Value | Specify with... | Example |
| :-------- | :------ | :------ |
-| List | :key($elem1, $elem2, ...) | :tags('Pod', 'Perl6') |
-| Hash | :key{$key1 => $value1, ...} | :feeds{url => 'perl6.org'} |
+| List | :key($elem1, $elem2, ...) | :tags('Pod', 'Raku') |
+| Hash | :key{$key1 => $value1, ...} | :feeds{url => 'raku.org'} |
| Boolean | :key/:key(True) | :skip-test(True) |
| Boolean | :!key/:key(False) | :!skip-test |
| String | :key('string') | :nonexec-reason('SyntaxError') |
@@ -450,7 +450,7 @@ we get the following output:
</pre>
This is highly dependent on the format output. For example, while this works
-when Pod is converted to HTML, it might not be preserved when converted
+when Pod is converted to HTML, it might not be preserved when converted
to Markdown.
### Block Pre-configuration
@@ -549,48 +549,48 @@ a Pod document, enclose them in a `E<>` code.
For example:
```
-Raku Perl 6 makes considerable use of the E<171> and E<187> characters.
-Raku Perl 6 makes considerable use of the E<laquo> and E<raquo> characters.
+Raku makes considerable use of the E<171> and E<187> characters.
+Raku makes considerable use of the E<laquo> and E<raquo> characters.
```
is rendered as:
-Raku Perl 6 makes considerable use of the « and » characters.
-Raku Perl 6 makes considerable use of the « and » characters.
+Raku makes considerable use of the « and » characters.
+Raku makes considerable use of the « and » characters.
## Rendering Pod
-To generate any output (i.e., Markdown, HTML, Text, etc.), you need to
-have the Raku Perl 6 compiler installed. In addition, you must install
+To generate any output (i.e., Markdown, HTML, Text, etc.), you need to
+have the Rakudo Raku compiler installed. In addition, you must install
a module (e.g., `Pod::To::Markdown`, `Pod::To::HTML`, `Pod::To::Text`, etc.)
that generates your desired output from Pod.
-For instructions about installing Raku Perl 6,
-[look here](https://perl6.org/downloads/).
+For instructions about installing Rakudo for running raku programs,
+[look here](https://raku.org/downloads/).
Run the following command to generate a certain output:
```
-perl6 --doc=TARGET input.pod6 > output.html
+raku --doc=TARGET input.pod6 > output.html
```
with `TARGET` being `Markdown`, `HTML`, `Text`, etc. Thus to generate
Markdown from Pod, run this:
```
-perl6 --doc=Markdown input.pod6 > output.html
+raku --doc=Markdown input.pod6 > output.html
```
## Accessing Pod
-In order to access Pod documentation from within a Raku Perl 6 program,
+In order to access Pod documentation from within a Raku program,
it is required to use the special `=` twigil (e.g., `$=pod`, `$=SYNOPSIS`,etc).
-The `$=` construct provides the introspection over the Pod structure,
+The `$=` construct provides the introspection over the Pod structure,
producing a `Pod::Block` tree root from which it is possible to access
the whole structure of the Pod document.
-If we place the following piece of Raku Perl 6 code and the Pod documentation
+If we place the following piece of Raku code and the Pod documentation
in the section [Semantic blocks](#semantic-blocks) in the same file:
```
@@ -615,8 +615,8 @@ AUTHOR
DESCRIPTION
```
-## Additional Information
+## Additional Information
-* <https://docs.perl6.org/language/pod> for the Pod documentation.
-* <https://docs.perl6.org/language/tables> for advices about Pod tables.
-* <https://design.perl6.org/S26.html> for the Pod specification.
+* <https://docs.raku.org/language/pod> for the Pod documentation.
+* <https://docs.raku.org/language/tables> for advices about Pod tables.
+* <https://design.raku.org/S26.html> for the Pod specification.
diff --git a/raku.html.markdown b/raku.html.markdown
index 4f397589..16035615 100644
--- a/raku.html.markdown
+++ b/raku.html.markdown
@@ -15,7 +15,7 @@ the JVM and the [MoarVM](http://moarvm.com).
Meta-note:
-* Although the pound sign (`#`) is used for sentences and notes, Pod-styled
+* Although the pound sign (`#`) is used for sentences and notes, Pod-styled
comments (more below about them) are used whenever it's convenient.
* `# OUTPUT:` is used to represent the output of a command to any standard
stream. If the output has a newline, it's represented by the `␤` symbol.
@@ -23,7 +23,7 @@ Meta-note:
* `#=>` represents the value of an expression, return value of a sub, etc.
In some cases, the value is accompanied by a comment.
* Backticks are used to distinguish and highlight the language constructs
- from the text.
+ from the text.
```perl6
####################################################
@@ -95,7 +95,7 @@ my @array = 'a', 'b', 'c';
# equivalent to:
my @letters = <a b c>;
# In the previous statement, we use the quote-words (`<>`) term for array
-# of words, delimited by space. Similar to perl5's qw, or Ruby's %w.
+# of words, delimited by space. Similar to perl's qw, or Ruby's %w.
@array = 1, 2, 4;
@@ -152,7 +152,7 @@ though.
=end comment
say %hash{'n'}; # OUTPUT: «2␤», gets value associated to key 'n'
say %hash<is-even>; # OUTPUT: «True␤», gets value associated to key 'is-even'
-
+
####################################################
# 2. Subroutines
####################################################
@@ -265,9 +265,9 @@ takes-a-bool('config', :bool); # OUTPUT: «config takes True␤»
takes-a-bool('config', :!bool); # OUTPUT: «config takes False␤»
=begin comment
-Since paranthesis can be omitted when calling a subroutine, you need to use
-`&` in order to distinguish between a call to a sub with no arguments and
-the code object.
+Since parenthesis can be omitted when calling a subroutine, you need to use
+`&` in order to distinguish between a call to a sub with no arguments and
+the code object.
For instance, in this example we must use `&` to store the sub `say-hello`
(i.e., the sub's code object) in a variable, not a subroutine call.
@@ -276,7 +276,7 @@ my &s = &say-hello;
my &other-s = sub { say "Anonymous function!" }
=begin comment
-A sub can have a "slurpy" parameter, or what one'd call a
+A sub can have a "slurpy" parameter, or what one'd call a
"doesn't-matter-how-many" parameter. This is Raku's way of supporting variadic
functions. For this, you must use `*@` (slurpy) which will "take everything
else". You can have as many parameters *before* a slurpy one, but not *after*.
@@ -284,8 +284,8 @@ else". You can have as many parameters *before* a slurpy one, but not *after*.
sub as-many($head, *@rest) {
@rest.join(' / ') ~ " !";
}
-say as-many('Happy', 'Happy', 'Birthday'); # OUTPUT: «Happy / Birthday !␤»
-say 'Happy', ['Happy', 'Birthday'], 'Day'; # OUTPUT: «Happy / Birthday / Day !␤»
+say as-many('Happy', 'Happy', 'Birthday'); # OUTPUT: «Happy / Birthday !␤»
+say as-many('Happy', ['Happy', 'Birthday'], 'Day'); # OUTPUT: «Happy / Birthday / Day !␤»
# Note that the splat (the *) did not consume the parameter before it.
@@ -298,7 +298,7 @@ arguments (or Iterable ones).
=end comment
sub b(**@arr) { @arr.perl.say };
b(['a', 'b', 'c']); # OUTPUT: «[["a", "b", "c"],]»
-b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]»
+b(1, $('d', 'e', 'f'), [2, 3]); # OUTPUT: «[1, ("d", "e", "f"), [2, 3]]»
b(1, [1, 2], ([3, 4], 5)); # OUTPUT: «[1, [1, 2], ([3, 4], 5)]␤»
=begin comment
@@ -508,7 +508,7 @@ given "foo bar" {
# can also be a C-style `for` loop:
loop {
say "This is an infinite loop !";
- last;
+ last;
}
# In the previous example, `last` breaks out of the loop very much
# like the `break` keyword in other languages.
@@ -614,8 +614,8 @@ say Int === Int; # OUTPUT: «True␤»
# Here are some common comparison semantics:
# String or numeric equality
-say 'Foo' ~~ 'Foo'; # OUTPU: «True␤», if strings are equal.
-say 12.5 ~~ 12.50; # OUTPU: «True␤», if numbers are equal.
+say 'Foo' ~~ 'Foo'; # OUTPUT: «True␤», if strings are equal.
+say 12.5 ~~ 12.50; # OUTPUT: «True␤», if numbers are equal.
# Regex - For matching a regular expression against the left side.
# Returns a `Match` object, which evaluates as True if regexp matches.
@@ -624,7 +624,7 @@ say $obj; # OUTPUT: «「a」␤»
say $obj.WHAT; # OUTPUT: «(Match)␤»
# Hashes
-say 'key' ~~ %hash; # OUTPUT:«True␤», if key exists in hash.
+say 'key' ~~ %hash; # OUTPUT: «True␤», if key exists in hash.
# Type - Checks if left side "is of type" (can check superclasses and roles).
say 1 ~~ Int; # OUTPUT: «True␤»
@@ -652,7 +652,7 @@ say 'a' le 'b'; # OUTPUT: «True␤»
# 5.2 Range constructor
#
-say 3 .. 7; # OUTPUT: «3..7␤», both included.
+say 3 .. 7; # OUTPUT: «3..7␤», both included.
say 3 ..^ 7; # OUTPUT: «3..^7␤», exclude right endpoint.
say 3 ^.. 7; # OUTPUT: «3^..7␤», exclude left endpoint.
say 3 ^..^ 7; # OUTPUT: «3^..^7␤», exclude both endpoints.
@@ -665,7 +665,7 @@ say 3.5 ~~ 3 ^.. 7; # OUTPUT: «True␤»,
# This is because the range `3 ^.. 7` only excludes anything strictly
# equal to 3. Hence, it contains decimals greater than 3. This could
-# mathematically be described as 3.5 ∈ (3,7] or in set notation,
+# mathematically be described as 3.5 ∈ (3,7] or in set notation,
# 3.5 ∈ { x | 3 < x ≤ 7 }.
say 3 ^.. 7 ~~ 4 .. 7; # OUTPUT: «False␤»
@@ -769,7 +769,7 @@ sub unpack_array( @array [$fst, $snd] ) {
# (^ remember the `[]` to interpolate the array)
}
unpack_array(@tail);
-# OUTPUT: «My first is 3, my second is 3! All in all, I'm 2 3.␤»
+# OUTPUT: «My first is 2, my second is 3! All in all, I'm 2 3.␤»
# If you're not using the array itself, you can also keep it anonymous,
# much like a scalar:
@@ -800,7 +800,7 @@ fst(1); # OUTPUT: «1␤»
=begin comment
You can also destructure hashes (and classes, which you'll learn about later).
-The syntax is basically the same as
+The syntax is basically the same as
`%hash-name (:key($variable-to-store-value-in))`.
The hash can stay anonymous if you only need the values you extracted.
@@ -842,7 +842,7 @@ my @list3 = list-of(3); #=> (0, 1, 2)
# 6.2 Lambdas (or anonymous subroutines)
#
-# You can create a lambda by using a pointy block (`-> {}`), a
+# You can create a lambda by using a pointy block (`-> {}`), a
# block (`{}`) or creating a `sub` without a name.
my &lambda1 = -> $argument {
@@ -858,18 +858,18 @@ my &lambda3 = sub ($argument) {
}
=begin comment
-Both pointy blocks and blocks are pretty much the same thing, except that
+Both pointy blocks and blocks are pretty much the same thing, except that
the former can take arguments, and that the latter can be mistaken as
-a hash by the parser. That being said, blocks can declare what's known
+a hash by the parser. That being said, blocks can declare what's known
as placeholders parameters through the twigils `$^` (for positional
-parameters) and `$:` (for named parameters). More on them latern on.
+parameters) and `$:` (for named parameters). More on them later on.
=end comment
my &mult = { $^numbers * $:times }
say mult 4, :times(6); #=> «24␤»
# Both pointy blocks and blocks are quite versatile when working with functions
-# that accepts other functions such as `map`, `grep`, etc. For example,
+# that accepts other functions such as `map`, `grep`, etc. For example,
# we add 3 to each value of an array using the `map` function with a lambda:
my @nums = 1..4;
my @res1 = map -> $v { $v + 3 }, @nums; # pointy block, explicit parameter
@@ -1088,7 +1088,7 @@ sub call_say_dyn {
# $*dyn_scoped 1 and 2 will be looked for in the call.
say_dyn(); # OUTPUT: «25 100␤»
-
+
# The call to `say_dyn` uses the value of $*dyn_scoped_1 from inside
# this sub's lexical scope even though the blocks aren't nested (they're
# call-nested).
@@ -1162,7 +1162,7 @@ class Human {
};
# Create a new instance of Human class.
-# NOTE: Only attributes declared with the `.` twigil can be set via the
+# NOTE: Only attributes declared with the `.` twigil can be set via the
# default constructor (more later on). This constructor only accepts named
# arguments.
my $person1 = Human.new(
@@ -1317,7 +1317,7 @@ method on the `$_` variable to access the exception
open 'foo' orelse say "Something happened {.exception}";
# This also works:
-open 'foo' orelse say "Something happened $_";
+open 'foo' orelse say "Something happened $_";
# OUTPUT: «Something happened Failed to open file foo: no such file or directory␤»
=begin comment
@@ -1431,15 +1431,15 @@ use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; # OUTPUT: «[1]␤»
=begin comment
-You should not declare packages using the `package` keyword (unlike Perl 5).
+You should not declare packages using the `package` keyword (unlike Perl).
Instead, use `class Package::Name::Here;` to declare a class, or if you only
want to export variables/subs, you can use `module` instead.
=end comment
# If `Hello` doesn't exist yet, it'll just be a "stub", that can be redeclared
-# as something else later.
+# as something else later.
module Hello::World { # bracketed form
- # declarations here
+ # declarations here
}
# The file-scoped form which extends until the end of the file. For
@@ -1520,7 +1520,7 @@ fixed-rand for ^10; # will print the same number 10 times
for ^5 -> $a {
sub foo {
# This will be a different value for every value of `$a`
- state $val = rand;
+ state $val = rand;
}
for ^5 -> $b {
# This will print the same value 5 times, but only 5. Next iteration
@@ -1558,9 +1558,9 @@ END { say "Runs at run time, as late as possible, only once" }
#
# 14.3 Block phasers
#
-ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" }
+ENTER { say "[*] Runs every time you enter a block, repeats on loop blocks" }
LEAVE {
- say "Runs everytime you leave a block, even when an exception
+ say "Runs every time you leave a block, even when an exception
happened. Repeats on loop blocks."
}
@@ -1610,7 +1610,7 @@ for ^5 {
#
# 14.6 Role/class phasers
#
-COMPOSE {
+COMPOSE {
say "When a role is composed into a class. /!\ NOT YET IMPLEMENTED"
}
@@ -1619,9 +1619,9 @@ say "This code took " ~ (time - CHECK time) ~ "s to compile";
# ... or clever organization:
class DB {
- method start-transaction { say "Starting transation!" }
- method commit { say "Commiting transaction..." }
- method rollback { say "Something went wrong. Rollingback!" }
+ method start-transaction { say "Starting transaction!" }
+ method commit { say "Committing transaction..." }
+ method rollback { say "Something went wrong. Rolling back!" }
}
sub do-db-stuff {
@@ -1647,7 +1647,7 @@ braces `{` and `}`.
=end comment
#
-# 15.1 `do` - It runs a block or a statement as a term.
+# 15.1 `do` - It runs a block or a statement as a term.
#
# Normally you cannot use a statement as a value (or "term"). `do` helps
@@ -1805,7 +1805,7 @@ sub postfix:<!>( Int $n ) {
}
say 5!; # OUTPUT: «120␤»
-# Postfix operators ('after') have to come *directly* after the term.
+# Postfix operators ('after') have to come *directly* after the term.
# No whitespace. You can use parentheses to disambiguate, i.e. `(5!)!`
sub infix:<times>( Int $n, Block $r ) { # infix ('between')
@@ -1898,7 +1898,7 @@ say [+] (); # OUTPUT: «0␤», empty sum
say [//]; # OUTPUT: «(Any)␤»
# There's no "default value" for `//`.
-# You can also use it with a function you made up,
+# You can also use it with a function you made up,
# You can also surround using double brackets:
sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; # OUTPUT: «6␤»
@@ -2078,19 +2078,19 @@ say so 'abc' ~~ / a b+ c /; # OUTPUT: «True␤», one is enough
say so 'abbbbc' ~~ / a b+ c /; # OUTPUT: «True␤», matched 4 "b"s
# `*` - zero or more matches
-say so 'ac' ~~ / a b* c /; # OUTPU: «True␤», they're all optional
-say so 'abc' ~~ / a b* c /; # OUTPU: «True␤»
-say so 'abbbbc' ~~ / a b* c /; # OUTPU: «True␤»
-say so 'aec' ~~ / a b* c /; # OUTPU: «False␤», "b"(s) are optional, not replaceable.
+say so 'ac' ~~ / a b* c /; # OUTPUT: «True␤», they're all optional
+say so 'abc' ~~ / a b* c /; # OUTPUT: «True␤»
+say so 'abbbbc' ~~ / a b* c /; # OUTPUT: «True␤»
+say so 'aec' ~~ / a b* c /; # OUTPUT: «False␤», "b"(s) are optional, not replaceable.
# `**` - (Unbound) Quantifier
# If you squint hard enough, you might understand why exponentation is used
# for quantity.
-say so 'abc' ~~ / a b**1 c /; # OUTPU: «True␤», exactly one time
-say so 'abc' ~~ / a b**1..3 c /; # OUTPU: «True␤», one to three times
-say so 'abbbc' ~~ / a b**1..3 c /; # OUTPU: «True␤»
-say so 'abbbbbbc' ~~ / a b**1..3 c /; # OUTPU: «Fals␤», too much
-say so 'abbbbbbc' ~~ / a b**3..* c /; # OUTPU: «True␤», infinite ranges are ok
+say so 'abc' ~~ / a b**1 c /; # OUTPUT: «True␤», exactly one time
+say so 'abc' ~~ / a b**1..3 c /; # OUTPUT: «True␤», one to three times
+say so 'abbbc' ~~ / a b**1..3 c /; # OUTPUT: «True␤»
+say so 'abbbbbbc' ~~ / a b**1..3 c /; # OUTPUT: «Fals␤», too much
+say so 'abbbbbbc' ~~ / a b**3..* c /; # OUTPUT: «True␤», infinite ranges are ok
#
# 18.2 `<[]>` - Character classes
@@ -2150,7 +2150,7 @@ say so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # OUTPUT: «True␤
say $/; # Will either print the matched object or `Nil` if nothing matched.
# As we also said before, it has array indexing:
-say $/[0]; # OUTPUT: «「ABC」 「ABC」␤»,
+say $/[0]; # OUTPUT: «「ABC」 「ABC」␤»,
# The corner brackets (「..」) represent (and are) `Match` objects. In the
# previous example, we have an array of them.
@@ -2202,8 +2202,8 @@ say $/[0].list.perl; # OUTPUT: «(Match.new(...),).list␤»
# Alternation - the `or` of regexes
# WARNING: They are DIFFERENT from PCRE regexps.
-say so 'abc' ~~ / a [ b | y ] c /; # OUTPU: «True␤», Either "b" or "y".
-say so 'ayc' ~~ / a [ b | y ] c /; # OUTPU: «True␤», Obviously enough...
+say so 'abc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Either "b" or "y".
+say so 'ayc' ~~ / a [ b | y ] c /; # OUTPUT: «True␤», Obviously enough...
# The difference between this `|` and the one you're used to is
# LTM ("Longest Token Matching") strategy. This means that the engine will
@@ -2218,7 +2218,7 @@ To decide which part is the "longest", it first splits the regex in two parts:
yet introduced), literals, characters classes and quantifiers.
* The "procedural part" includes everything else: back-references,
- code assertions, and other things that can't traditionnaly be represented
+ code assertions, and other things that can't traditionally be represented
by normal regexps.
Then, all the alternatives are tried at once, and the longest wins.
@@ -2268,7 +2268,7 @@ while its absence falseness). For example:
# convert to IO object to check the file exists
subset File of Str where *.IO.d;
-
+
multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
@@ -2358,7 +2358,7 @@ side, once its left side changed:
# In this case the right-hand-side wasn't tested until `$_` became "C"
# (and thus did not match instantly).
-.say if 'B' fff 'B' for <A B C B A>; #=> «B C B␤»,
+.say if 'B' fff 'B' for <A B C B A>; #=> «B C B␤»,
# A flip-flop can change state as many times as needed:
for <test start print it stop not printing start print again stop not anymore> {
@@ -2392,21 +2392,20 @@ resource on Raku. If you are looking for something, use the search bar.
This will give you a dropdown menu of all the pages referencing your search
term (Much better than using Google to find Raku documents!).
-- Read the [Raku Advent Calendar](http://perl6advent.wordpress.com/). This
+- Read the [Raku Advent Calendar](https://rakuadventcalendar.wordpress.com/). This
is a great source of Raku snippets and explanations. If the docs don't
describe something well enough, you may find more detailed information here.
This information may be a bit older but there are many great examples and
explanations. Posts stopped at the end of 2015 when the language was declared
-stable and Raku 6.c was released.
+stable and `Raku v6.c` was released.
-- Come along on `#raku` at `irc.freenode.net`. The folks here are
+- Come along on `#raku` at [`irc.freenode.net`](https://webchat.freenode.net/?channels=#raku). The folks here are
always helpful.
- Check the [source of Raku's functions and
-classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is
+classes](https://github.com/rakudo/rakudo/tree/master/src/core.c). Rakudo is
mainly written in Raku (with a lot of NQP, "Not Quite Perl", a Raku subset
easier to implement and optimize).
- Read [the language design documents](https://design.raku.org/). They explain
Raku from an implementor point-of-view, but it's still very interesting.
-
diff --git a/rst.html.markdown b/rst.html.markdown
index 2423622e..bdc73c7a 100644
--- a/rst.html.markdown
+++ b/rst.html.markdown
@@ -49,9 +49,11 @@ Subtitles with dashes
You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``print()``.
+Special characters can be escaped using a backslash, e.g. \\ or \*.
+
Lists are similar to Markdown, but a little more involved.
-Remember to line up list symbols (like - or *) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:
+Remember to line up list symbols (like - or \*) with the left edge of the previous text block, and remember to use blank lines to separate new lists from parent lists:
- First item
- Second item
@@ -86,7 +88,7 @@ There are multiple ways to make links:
- By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link)
- By making a more Markdown-like link: `Github <https://github.com/>`_ .
-.. _Github https://github.com/
+.. _Github: https://github.com/
```
diff --git a/ru-ru/pascal-ru.html.markdown b/ru-ru/pascal-ru.html.markdown
new file mode 100644
index 00000000..8a41918f
--- /dev/null
+++ b/ru-ru/pascal-ru.html.markdown
@@ -0,0 +1,216 @@
+---
+language: Pascal
+filename: learnpascal-ru.pas
+contributors:
+ - ["Ganesha Danu", "http://github.com/blinfoldking"]
+ - ["Keith Miyake", "https://github.com/kaymmm"]
+translators:
+ - ["Anton 'Dart' Nikolaev", "https://github.com/dartfnm"]
+---
+
+
+>Pascal - это процедурный язык программирования, который Никлаус Вирт разработал в 1968–69 годах и опубликовал в 1970 году как небольшой эффективный язык, предназначенный для поощрения хороших методов программирования с использованием структурированного программирования и структурирования данных. Он назван в честь французского математика, философа и физика Блеза Паскаля.
+>
+>source : [wikipedia](https://ru.wikipedia.org/wiki/Паскаль_(язык_программирования)))
+
+
+
+Для компиляции и запуска программы на языке Паскаль вы можете использовать бесплатный компилятор FreePascal. [Скачать здесь](https://www.freepascal.org/)
+
+Либо современный бесплатный компилятор Паскаля нового поколения под платформу .Net [PascalABC.NET](http://pascalabc.net)
+
+```pascal
+// это комментарий
+{
+ а вот это:
+ - комментарий на несколько строк
+}
+
+//объявляем имя программы
+program learn_pascal; //<-- не забываем ставить точку с запятой (;)
+
+const
+ {
+ это секция в которой вы должны объявлять константы
+ }
+type
+ {
+ здесь вы можете объявлять собственные типы данных
+ }
+var
+ {
+ секция для объявления переменных
+ }
+
+begin //начало основной программы
+ {
+ тело вашей программы
+ }
+end. // В конце основной программы обязательно должна стоять точка "."
+```
+
+```pascal
+//объявление переменных
+//вы можете сделать так
+var a:integer;
+var b:integer;
+//или так
+var
+ a : integer;
+ b : integer;
+//или даже так
+var a,b : integer;
+```
+
+```pascal
+program Learn_More;
+
+// Познакомимся с типами данных и с их операциями
+const
+ PI = 3.141592654;
+ GNU = 'GNU''s Not Unix';
+ // имена константам принято давать ЗАГЛАВНЫМИ_БУКВАМИ (в верхнем регистре)
+ // их значения фиксированны т.е никогда не меняются во время выполнения программы
+ // содержат любой стандартный тип данных (integer, real, boolean, char, string)
+
+type
+ ch_array : array [0..255] of char;
+ // массивы - это составной тип данных
+ // мы указываем индекс первого и последнего элемента массива ([0..255])
+ // здесь мы объявили новый тип данных содержащий 255 символов 'char'
+ // (по сути, это просто строка - string[256])
+
+ md_array : array of array of integer;
+ // массив в массиве - по сути является двумерным массивом
+ // можно задать массив нулевой (0) длины, а потом динамически расширить его
+ // это двумерный массив целых чисел
+
+//Объявление переменных
+var
+ int, c, d : integer;
+ // три переменные, которые содержат целые числа
+ // Тип "integer" это 16-битное число в диапазоне [-32,768..32,767]
+ r : real;
+ // переменная типа "real" принимает вещественные (дробные) значения
+ // в диапазоне [3.4E-38..3.4E38]
+ bool : boolean;
+ // переменная логического типа, принимающая булевы-значения: True/False (Правда/Ложь)
+ ch : char;
+ // эта переменная содержит значение кода одного символа
+ // тип 'char' это 8-битное число (1 байт), так что никакого Юникода
+ str : string;
+ // это переменная составного типа, являющееся строкой
+ // по сути, строка это массив в 255 символов длиною, по умолчанию
+
+ s : string[50];
+ // эта строка может содержать максимум 50 символов
+ // вы можете сами указать длину строки, чтобы минимизировать использование памяти
+ my_str: ch_array;
+ // вы можете объявлять переменные собственных типов
+ my_2d : md_array;
+ // динамически расширяемые массивы требуют указания длины перед их использованием.
+
+ // дополнительные целочисленные типы данных
+ b : byte; // диапазон [0..255]
+ shi : shortint; // диапазон [-128..127]
+ smi : smallint; // диапазон [-32,768..32,767] (стандартный Integer)
+ w : word; // диапазон [0..65,535]
+ li : longint; // диапазон [-2,147,483,648..2,147,483,647]
+ lw : longword; // диапазон [0..4,294,967,295]
+ c : cardinal; // тоже что и longword
+ i64 : int64; // диапазон [-9223372036854775808..9223372036854775807]
+ qw : qword; // диапазон [0..18,446,744,073,709,551,615]
+
+ // дополнительные вещественные типы данных (дробные)
+ rr : real; // диапазон зависит от платформы (т.е. 8-бит, 16-бит и т.д.)
+ rs : single; // диапазон [1.5E-45..3.4E38]
+ rd : double; // диапазон [5.0E-324 .. 1.7E308]
+ re : extended; // диапазон [1.9E-4932..1.1E4932]
+ rc : comp; // диапазон [-2E64+1 .. 2E63-1]
+
+Begin
+ int := 1; // так мы присваиваем значение переменной
+ r := 3.14;
+ ch := 'a';
+ str := 'apple';
+ bool := true;
+ // Паскаль не чувствителен к регистру
+
+ // арифметические операции
+ int := 1 + 1; // int = 2; заменяет предыдущее значение
+ int := int + 1; // int = 2 + 1 = 3;
+ int := 4 div 2; //int = 2; 'div' операция деления, с отбрасыванием дробной части
+ int := 3 div 2; //int = 1;
+ int := 1 div 2; //int = 0;
+
+ bool := true or false; // bool = true
+ bool := false and true; // bool = false
+ bool := true xor true; // bool = false
+
+ r := 3 / 2; // деления вещественных чисел с дробной частью
+ r := int; // вещественной переменной можно присвоить целочисленное значение, но не наоборот
+
+ my_str[0] := 'a'; // для доступа к элементу массива нужно указать его индекс в квадратных скобках ([0])
+
+ c := str[1]; // первая буква во всех Строках находится по индексу [1]
+ str := 'hello' + 'world'; //объединяем 2 строки в одну
+
+ SetLength(my_2d,10,10); // инициализируем динамически расширяемый массив
+ // задаём размер 2х-мерного массива 10×10
+
+ // первый элемент массива лежит в индексе [0], последний [длина_массива-1]
+ for c := 0 to 9 do
+ for d := 0 to 9 do // переменные для счетчиков циклов должны быть объявлены
+ my_2d[c,d] := c * d;
+ // обращаться к многомерным массивам нужно с помощью одного набора скобок
+
+End.
+```
+
+```pascal
+program Functional_Programming;
+
+Var
+ i, dummy : integer;
+
+function factorial_recursion(const a: integer) : integer;
+{ Функция расчёта Факториала целочисленного параметра 'a', рекурсивно. Возвращает целое значение }
+
+// Мы можем объявлять локальные переменные внутри своей функции:
+// Var
+// local_a : integer;
+
+Begin
+ If a >= 1 Then
+ factorial_recursion := a * factorial_recursion(a-1)
+ // возвращаем результат, присваивая найденное значение переменной с тем же именем, как у функции
+ Else
+ factorial_recursion := 1;
+End; // Для завершения функции, используется символ ";" после оператора "End;"
+
+
+
+procedure get_integer( var i : integer; dummy : integer );
+{ Эта процедура ждёт от пользователя ввода целого числа и возвращает его значение через параметр i.
+ Если параметр функции начинается с 'var', это означает, что его значение было передано, по ссылке, то есть, оно может использоваться не только как входное значение, но и для возвращения дополнительных результатов работы функции.
+ Параметры функции (без 'var'), (такие как "dummy" (пустышка)), передаются по значению, и по сути являются - локальными переменными, таким образом изменения, внесенные внутри функции/процедуры, не влияют на значение переменной за её пределами.
+}
+Begin // начало процедуры
+ write('Введите целое число: ');
+ readln(i); // число, введённое пользователем, сохранится в переменной i
+ // и её значение будет доступно вызывающей подпрограмме
+
+ dummy := 4; // значение 'dummy' не будет влиять на значения переменной вне процедуры
+End; // конец процедуры
+
+Begin // главный блок программы
+ dummy := 3;
+ get_integer(i, dummy); // вызываем процедуру получения числа от пользователя
+ writeln(i, '! = ', factorial_recursion(i)); // ввыводим значение факториала от i
+
+ writeln('dummy = ', dummy);
+ // всегда выводит "3", поскольку фиктивная переменная не изменяется.
+End. // конец программы
+
+```
+
diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown
index a907ba41..a9bb683b 100644
--- a/ru-ru/perl-ru.html.markdown
+++ b/ru-ru/perl-ru.html.markdown
@@ -9,12 +9,12 @@ translators:
lang: ru-ru
---
-Perl 5 -- высокоуровневый мощный язык с 25-летней историей.
-Особенно хорош для обработки разнообразных текстовых данных.
+Perl -- высокоуровневый мощный язык с 25-летней историей.
+Особенно хорош для обработки разнообразных текстовых данных.
-Perl 5 работает более чем на 100 платформах, от портативных устройств
-до мейнфреймов, и подходит как для быстрого прототипирования,
-так и для крупных проектов.
+Perl работает более чем на 100 платформах, от портативных устройств
+до мейнфреймов, и подходит как для быстрого прототипирования,
+так и для крупных проектов.
```perl
# Комментарии начинаются с символа решетки.
@@ -23,8 +23,8 @@ Perl 5 работает более чем на 100 платформах, от п
#### Типы переменных в Perl
# Скалярные переменные начинаются с знака доллара $.
-# Имя переменной состоит из букв, цифр и знаков подчеркивания,
-# начиная с буквы или подчеркивания.
+# Имя переменной состоит из букв, цифр и знаков подчеркивания,
+# начиная с буквы или подчеркивания.
### В Perl три основных типа переменных: скаляры, массивы, хеши.
@@ -55,7 +55,7 @@ my %fruit_color = (
banana => "yellow",
);
-# Важно: вставка и поиск в хеше выполняются за константное время,
+# Важно: вставка и поиск в хеше выполняются за константное время,
# независимо от его размера.
# Скаляры, массивы и хеши подробно описаны в разделе perldata
@@ -81,7 +81,7 @@ unless ( condition ) {
}
# Это более читаемый вариант для "if (!condition)"
-# Специфические Perl-овые пост-условия:
+# Специфические Perl-овые пост-условия:
print "Yow!" if $zippy;
print "We have no bananas" unless $bananas;
@@ -129,7 +129,7 @@ open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
# Читать из файлового дескриптора можно с помощью оператора "<>".
-# В скалярном контексте он читает одну строку из файла, в списковом --
+# В скалярном контексте он читает одну строку из файла, в списковом --
# читает сразу весь файл, сохраняя по одной строке в элементе массива:
my $line = <$in>;
@@ -152,13 +152,13 @@ logger("We have a logger subroutine!");
#### Perl-модули
-Perl-овые модули предоставляют широкий набор функциональности,
-так что вы можете не изобретать заново велосипеды, а просто скачать
-нужный модуль с CPAN (http://www.cpan.org/).
-Некоторое количество самых полезных модулей включено в стандартную
+Perl-овые модули предоставляют широкий набор функциональности,
+так что вы можете не изобретать заново велосипеды, а просто скачать
+нужный модуль с CPAN (http://www.cpan.org/).
+Некоторое количество самых полезных модулей включено в стандартную
поставку Perl.
-Раздел документации perlfaq содержит вопросы и ответы о многих частых
+Раздел документации perlfaq содержит вопросы и ответы о многих частых
задачах, и часто предлагает подходящие CPAN-модули.
diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown
index b1fd04e1..8b263be6 100644
--- a/ru-ru/ruby-ru.html.markdown
+++ b/ru-ru/ruby-ru.html.markdown
@@ -480,7 +480,7 @@ class Human
@name
end
- # Тоже самое можно определить с помощью att_accessor
+ # Тоже самое можно определить с помощью attr_accessor
attr_accessor :name
# Также можно создать методы только для записи или чтения
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 376f4a47..d21c727f 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -430,6 +430,16 @@ def guests(*array)
array.each { |guest| puts guest }
end
+# There is also the shorthand block syntax. It's most useful when you need
+# to call a simple method on all array items.
+upcased = ['Watch', 'these', 'words', 'get', 'upcased'].map(&:upcase)
+puts upcased
+#=> ["WATCH", "THESE", "WORDS", "GET", "UPCASED"]
+
+sum = [1, 2, 3, 4, 5].reduce(&:+)
+puts sum
+#=> 15
+
# Destructuring
# Ruby will automatically destructure arrays on assignment to multiple variables.
diff --git a/scala.html.markdown b/scala.html.markdown
index c7a8842e..08fd37e4 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -252,7 +252,7 @@ weirdSum(2, 4) // => 16
// The return keyword exists in Scala, but it only returns from the inner-most
// def that surrounds it.
// WARNING: Using return in Scala is error-prone and should be avoided.
-// It has no effect on anonymous functions. For example:
+// It has no effect on anonymous functions. For example here you may expect foo(7) should return 17 but it returns 7:
def foo(x: Int): Int = {
val anonFunc: Int => Int = { z =>
if (z > 5)
@@ -260,9 +260,10 @@ def foo(x: Int): Int = {
else
z + 2 // This line is the return value of anonFunc
}
- anonFunc(x) // This line is the return value of foo
+ anonFunc(x) + 10 // This line is the return value of foo
}
+foo(7) // => 7
/////////////////////////////////////////////////
// 3. Flow Control
diff --git a/set-theory.html.markdown b/set-theory.html.markdown
new file mode 100644
index 00000000..c6bc39c5
--- /dev/null
+++ b/set-theory.html.markdown
@@ -0,0 +1,162 @@
+---
+category: Algorithms & Data Structures
+name: Set theory
+contributors:
+---
+The set theory is a study for sets, their operations, and their properties. It is the basis of the whole mathematical system.
+
+* A set is a collection of definite distinct items.
+
+## Basic operators
+These operators don't require a lot of text to describe.
+
+* `∨` means or.
+* `∧` means and.
+* `,` separates the filters that determine the items in the set.
+
+## A brief history of the set theory
+### Naive set theory
+* Cantor invented the naive set theory.
+* It has lots of paradoxes and initiated the third mathematical crisis.
+
+### Axiomatic set theory
+* It uses axioms to define the set theory.
+* It prevents paradoxes from happening.
+
+## Built-in sets
+* `∅`, the set of no items.
+* `N`, the set of all natural numbers. `{0,1,2,3,…}`
+* `Z`, the set of all integers. `{…,-2,-1,0,1,2,…}`
+* `Q`, the set of all rational numbers.
+* `R`, the set of all real numbers.
+
+### The empty set
+* The set containing no items is called the empty set. Representation: `∅`
+* The empty set can be described as `∅ = {x|x ≠ x}`
+* The empty set is always unique.
+* The empty set is the subset of all sets.
+
+```
+A = {x|x∈N,x < 0}
+A = ∅
+∅ = {} (Sometimes)
+
+|∅| = 0
+|{∅}| = 1
+```
+
+## Representing sets
+### Enumeration
+* List all items of the set, e.g. `A = {a,b,c,d}`
+* List some of the items of the set. Ignored items are represented with `…`. E.g. `B = {2,4,6,8,10,…}`
+
+### Description
+* Describes the features of all items in the set. Syntax: `{body|condtion}`
+
+```
+A = {x|x is a vowel}
+B = {x|x ∈ N, x < 10l}
+C = {x|x = 2k, k ∈ N}
+C = {2x|x ∈ N}
+```
+
+## Relations between sets
+### Belongs to
+* If the value `a` is one of the items of the set `A`, `a` belongs to `A`. Representation: `a∈A`
+* If the value `a` is not one of the items of the set `A`, `a` does not belong to `A`. Representation: `a∉A`
+
+### Equals
+* If all items in a set are exactly the same to another set, they are equal. Representation: `a=b`
+* Items in a set are not order sensitive. `{1,2,3,4}={2,3,1,4}`
+* Items in a set are unique. `{1,2,2,3,4,3,4,2}={1,2,3,4}`
+* Two sets are equal if and only if all of their items are exactly equal to each other. Representation: `A=B`. Otherwise, they are not equal. Representation: `A≠B`.
+* `A=B` if `A ⊆ B` and `B ⊆ A`
+
+### Belongs to
+* If the set A contains an item `x`, `x` belongs to A (`x∈A`).
+* Otherwise, `x` does not belong to A (`x∉A`).
+
+### Subsets
+* If all items in a set `B` are items of set `A`, we say that `B` is a subset of `A` (`B⊆A`).
+* If B is not a subset of A, the representation is `B⊈A`.
+
+### Proper subsets
+* If `B ⊆ A` and `B ≠ A`, B is a proper subset of A (`B ⊂ A`). Otherwise, B is not a proper subset of A (`B ⊄ A`).
+
+## Set operations
+### Base number
+* The number of items in a set is called the base number of that set. Representation: `|A|`
+* If the base number of the set is finite, this set is a finite set.
+* If the base number of the set is infinite, this set is an infinite set.
+
+```
+A = {A,B,C}
+|A| = 3
+B = {a,{b,c}}
+|B| = 2
+|∅| = 0 (it has no items)
+```
+
+### Powerset
+* Let `A` be any set. The set that contains all possible subsets of `A` is called a powerset (written as `P(A)`).
+
+```
+P(A) = {x|x ⊆ A}
+
+|A| = N, |P(A)| = 2^N
+```
+
+## Set operations among two sets
+### Union
+Given two sets `A` and `B`, the union of the two sets are the items that appear in either `A` or `B`, written as `A ∪ B`.
+
+```
+A ∪ B = {x|x∈A∨x∈B}
+```
+
+### Intersection
+Given two sets `A` and `B`, the intersection of the two sets are the items that appear in both `A` and `B`, written as `A ∩ B`.
+
+```
+A ∩ B = {x|x∈A,x∈B}
+```
+
+### Difference
+Given two sets `A` and `B`, the set difference of `A` with `B` is every item in `A` that does not belong to `B`.
+
+```
+A \ B = {x|x∈A,x∉B}
+```
+
+### Symmetrical difference
+Given two sets `A` and `B`, the symmetrical difference is all items among `A` and `B` that doesn't appear in their intersections.
+
+```
+A △ B = {x|(x∈A∧x∉B)∨(x∈B∧x∉A)}
+
+A △ B = (A \ B) ∪ (B \ A)
+```
+
+### Cartesian product
+Given two sets `A` and `B`, the cartesian product between `A` and `B` consists of a set containing all combinations of items of `A` and `B`.
+
+```
+A × B = { {x, y} | x ∈ A, y ∈ B }
+```
+
+## "Generalized" operations
+### General union
+Better known as "flattening" of a set of sets.
+
+```
+∪A = {x|X∈A,x∈X}
+∪A={a,b,c,d,e,f}
+∪B={a}
+∪C=a∪{c,d}
+```
+
+### General intersection
+
+```
+∩ A = A1 ∩ A2 ∩ … ∩ An
+```
diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown
index d6d369cc..58dccae4 100644
--- a/smalltalk.html.markdown
+++ b/smalltalk.html.markdown
@@ -388,7 +388,7 @@ y := $A max: $B.
```smalltalk
| b x y |
x := #Hello. "symbol assignment"
-y := 'String', 'Concatenation'. "symbol concatenation (result is string)"
+y := #Symbol, #Concatenation. "symbol concatenation (result is string)"
b := x isEmpty. "test if symbol is empty"
y := x size. "string size"
y := x at: 2. "char at location"
diff --git a/vim.html.markdown b/vim.html.markdown
index 5b84a3ea..27d90f18 100644
--- a/vim.html.markdown
+++ b/vim.html.markdown
@@ -24,6 +24,7 @@ specific points in the file, and for fast editing.
ZZ # Save file and quit vim
:q! # Quit vim without saving file
# ! *forces* :q to execute, hence quiting vim without saving
+ ZQ # Quit vim without saving file
:x # Save file and quit vim, shorter version of :wq
u # Undo
@@ -181,6 +182,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns':
~ # Toggle letter case of selected text
u # Selected text to lower case
U # Selected text to upper case
+ J # Join the current line with the next line
# Fold text
zf # Create fold from selected text
diff --git a/wasm.html.markdown b/wasm.html.markdown
index aba2084f..81344abe 100644
--- a/wasm.html.markdown
+++ b/wasm.html.markdown
@@ -61,7 +61,7 @@ contributors:
;; We have to use the right data type for each operation:
;; (local.set $mult_result (f32.mul (f32.const 2.0) (f32.const 4.0))) ;; WRONG! mult_result is f64!
- (local.set $mult_result (f64.mul (f64.const 2.0) (f64.const 4.0))) ;; WRONG! mult_result is f64!
+ (local.set $mult_result (f64.mul (f64.const 2.0) (f64.const 4.0)))
;; WebAssembly has some builtin operations, like basic math and bitshifting.
;; Notably, it does not have built in trigonometric functions.
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index 8eecc56e..7286fa9f 100644
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -128,7 +128,7 @@ printf("Enter the array size: "); // 询问用户数组长度
char buf[0x100];
fgets(buf, sizeof buf, stdin);
-// stroul 将字符串解析为无符号整数
+// strtoul 将字符串解析为无符号整数
size_t size = strtoul(buf, NULL, 10);
int var_length_array[size]; // 声明VLA
printf("sizeof array = %zu\n", sizeof var_length_array);
diff --git a/zh-cn/perl-cn.html.markdown b/zh-cn/perl-cn.html.markdown
index 5b0d6179..4421da6e 100644
--- a/zh-cn/perl-cn.html.markdown
+++ b/zh-cn/perl-cn.html.markdown
@@ -10,9 +10,9 @@ translators:
lang: zh-cn
---
-Perl 5是一个功能强大、特性齐全的编程语言,有25年的历史。
+Perl 是一个功能强大、特性齐全的编程语言,有25年的历史。
-Perl 5可以在包括便携式设备和大型机的超过100个平台上运行,既适用于快速原型构建,也适用于大型项目开发。
+Perl 可以在包括便携式设备和大型机的超过100个平台上运行,既适用于快速原型构建,也适用于大型项目开发。
```perl
# 单行注释以#号开头