mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-04-27 07:33:57 +00:00
Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
b8ba98c86c
@ -73,9 +73,9 @@ echo Hello, $NAME!
|
||||
# use 'man test' for more info about conditionals
|
||||
if [ $NAME -ne $USER ]
|
||||
then
|
||||
echo "Your name is your username"
|
||||
else
|
||||
echo "Your name isn't your username"
|
||||
else
|
||||
echo "Your name is your username"
|
||||
fi
|
||||
|
||||
# There is also conditional execution
|
||||
|
106
de-de/coffeescript-de.html.markdown
Normal file
106
de-de/coffeescript-de.html.markdown
Normal file
@ -0,0 +1,106 @@
|
||||
---
|
||||
language: coffeescript
|
||||
contributors:
|
||||
- ["Tenor Biel", "http://github.com/L8D"]
|
||||
- ["Xavier Yao", "http://github.com/xavieryao"]
|
||||
translators:
|
||||
- ["Frederik Ring", "https://github.com/m90"]
|
||||
- ["Philipp Fischbeck", "https://github.com/PFischbeck"]
|
||||
filename: coffeescript-de.coffee
|
||||
lang: de-de
|
||||
---
|
||||
|
||||
CoffeeScript ist eine kleine Sprache, die eins zu eins nach JavaScript übersetzt wird - es findet keine Interpretation zur Laufzeit statt.
|
||||
Als Nachfolger von JavaScript konzipiert, gibt CoffeeScript sein Bestes, lesbaren, gut formatierten und sauber laufenden JavaScript-Code zu erzeugen, der in jeder JavaScript-Laufzeit einwandfrei funktioniert.
|
||||
|
||||
Auf [der CoffeeScript Website](http://coffeescript.org/) gibt es ein ausführliches Tutorial.
|
||||
|
||||
``` coffeescript
|
||||
# CoffeeScript ist eine dieser Sprachen für "Hipster"
|
||||
# und folgt daher vielen Trends und Einflüssen aus modernen Sprachen.
|
||||
# Kommentare werden daher wie in Ruby und Python mit Hashes gekennzeichnet
|
||||
|
||||
###
|
||||
Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *'s und '* /'s
|
||||
im erzeugten JavaScript umgewandelt.
|
||||
|
||||
Vorweg: bevor du mit CoffeeScript anfängst, solltest du bereits einen guten
|
||||
Überblick über die Sprache JavaScript haben.
|
||||
###
|
||||
|
||||
# Zuweisung:
|
||||
number = 42 #=> var number = 42;
|
||||
opposite = true #=> var opposite = true;
|
||||
|
||||
# Bedingungen:
|
||||
number = -42 if opposite #=> if(opposite) { number = -42; }
|
||||
|
||||
# Funktionen:
|
||||
square = (x) -> x * x #=> var square = function(x) { return x * x; }
|
||||
|
||||
fill = (container, liquid = "Kaffee") ->
|
||||
"#{container} wird mit #{liquid} gefüllt..."
|
||||
#=>var fill;
|
||||
#
|
||||
#fill = function(container, liquid) {
|
||||
# if (liquid == null) {
|
||||
# liquid = "Kaffee";
|
||||
# }
|
||||
# return container + " wird mit " + liquid + " gefüllt...";
|
||||
#};
|
||||
|
||||
# "Ranges":
|
||||
list = [1..5] #=> var list = [1, 2, 3, 4, 5];
|
||||
|
||||
# Objekte:
|
||||
math =
|
||||
root: Math.sqrt
|
||||
square: square
|
||||
cube: (x) -> x * square x
|
||||
#=> var math = {
|
||||
# "root": Math.sqrt,
|
||||
# "square": square,
|
||||
# "cube": function(x) { return x * square(x); }
|
||||
#}
|
||||
|
||||
# "Splats":
|
||||
race = (winner, runners...) ->
|
||||
print winner, runners
|
||||
#=>race = function() {
|
||||
# var runners, winner;
|
||||
# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
|
||||
# return print(winner, runners);
|
||||
#};
|
||||
|
||||
# Existenz-Operator:
|
||||
alert "Hab ich's nicht gesagt?" if elvis?
|
||||
#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Hab ich's nicht gesagt?"); }
|
||||
|
||||
# Listen-Abstraktion:
|
||||
cubes = (math.cube num for num in list)
|
||||
#=>cubes = (function() {
|
||||
# var _i, _len, _results;
|
||||
# _results = [];
|
||||
# for (_i = 0, _len = list.length; _i < _len; _i++) {
|
||||
# num = list[_i];
|
||||
# _results.push(math.cube(num));
|
||||
# }
|
||||
# return _results;
|
||||
# })();
|
||||
|
||||
foods = ['Brokkoli', 'Spinat', 'Schokolade']
|
||||
eat food for food in foods when food isnt 'Schokolade'
|
||||
#=>foods = ['Brokkoli', 'Spinat', 'Schokolade'];
|
||||
#
|
||||
#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
|
||||
# food = foods[_k];
|
||||
# if (food !== 'Schokolade') {
|
||||
# eat(food);
|
||||
# }
|
||||
#}
|
||||
```
|
||||
|
||||
## Weiterführende Links
|
||||
|
||||
- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
|
||||
- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
|
@ -79,7 +79,7 @@ func learnTypes() {
|
||||
Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
|
||||
|
||||
// nicht-ASCII Literal. Go Quelltext ist UTF-8 kompatibel.
|
||||
g := 'Σ' // Ein Runen-Typ, alias uint32, gebraucht für unicode code points.
|
||||
g := 'Σ' // Ein Runen-Typ, alias int32, gebraucht für unicode code points.
|
||||
|
||||
f := 3.14195 // float64, eine IEEE-754 64-bit Dezimalzahl
|
||||
c := 3 + 4i // complex128, besteht intern aus zwei float64-er
|
||||
|
@ -77,7 +77,7 @@ func learnTypes() {
|
||||
saltos de línea.` // mismo tipo cadena
|
||||
|
||||
// Literal no ASCII. Los fuentes de Go son UTF-8.
|
||||
g := 'Σ' // Tipo rune, un alias de uint32, alberga un punto unicode.
|
||||
g := 'Σ' // Tipo rune, un alias de int32, alberga un punto unicode.
|
||||
f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit.
|
||||
c := 3 + 4i // complex128, representado internamente por dos float64.
|
||||
// Sintaxis Var con inicializadores.
|
||||
|
@ -7,23 +7,24 @@ contributors:
|
||||
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
||||
translators:
|
||||
- ["Francisco Gomez", "http://github.com/frncscgmz"]
|
||||
- ["Joaquín Ferrero", "http://github.com/joaquinferrero"]
|
||||
lang: es-es
|
||||
---
|
||||
|
||||
Perl 5 es un lenguaje de programación altamente capaz, rico en características con mas de 25 años de desarrollo.
|
||||
Perl 5 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 mas de 100 plataformas desde portales hasta mainframes y es adecuado para realizar prototipos rápidos hasta desarrollar proyectos a gran escala.
|
||||
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
|
||||
# Comentarios de una sola linea con un carácter hash.
|
||||
# Comentarios de una sola línea con un carácter hash
|
||||
|
||||
#### Tipos de variables en Perl
|
||||
|
||||
# Las variables comienzan con el símbolo $.
|
||||
# Un nombre de variable valido empieza con una letra o un guión bajo,
|
||||
# seguido por cualquier numero de letras, números o guiones bajos.
|
||||
# Las variables comienzan con el símbolo $
|
||||
# Un nombre de variable válido empieza con una letra o un guión bajo,
|
||||
# seguido por cualquier número de letras, números o guiones bajos
|
||||
|
||||
### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes.
|
||||
### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes
|
||||
|
||||
## Escalares
|
||||
# Un escalar representa un solo valor:
|
||||
@ -31,99 +32,98 @@ my $animal = "camello";
|
||||
my $respuesta = 42;
|
||||
|
||||
# Los valores escalares pueden ser cadenas de caracteres, números enteros o
|
||||
# de punto flotante, Perl automáticamente los convertirá como sea requerido.
|
||||
# de punto flotante; Perl automáticamente los convertirá como sea requerido
|
||||
|
||||
## Arreglos
|
||||
# Un arreglo representa una lista de valores:
|
||||
my @animales = {"camello","llama","buho"};
|
||||
my @numeros = {23,42,69};
|
||||
my @mixto = {"camello",42,1.23};
|
||||
|
||||
|
||||
my @animales = ("camello","llama","buho"};
|
||||
my @numeros = (23, 42, 69);
|
||||
my @mixto = ("camello", 42, 1.23);
|
||||
|
||||
## Hashes
|
||||
# Un hash representa un conjunto de pares llave/valor:
|
||||
|
||||
my %color_fruta = {"manzana","rojo","banana","amarillo"};
|
||||
|
||||
# Puedes usar un espacio en blanco y el operador "=>" para asignarlos mas
|
||||
# fácilmente.
|
||||
# Un hash representa un conjunto de pares llave/valor:
|
||||
my %color_fruta = ("manzana","rojo","banana","amarillo");
|
||||
|
||||
# Puede usar un espacio en blanco y el operador "=>" para asignarlos más fácilmente
|
||||
my %color_fruta = (
|
||||
manzana => "rojo",
|
||||
banana => "amarillo",
|
||||
);
|
||||
# Los escalares, arreglos y hashes están mas documentados en perldata. (perldoc perldata).
|
||||
);
|
||||
|
||||
# Los tipos de datos mas complejos pueden ser construidos utilizando
|
||||
# referencias, las cuales te permiten construir listas y hashes dentro
|
||||
# de listas y hashes.
|
||||
# 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
|
||||
# referencias, las cuales le permiten construir listas y hashes dentro
|
||||
# de listas y hashes
|
||||
|
||||
#### Estructuras condicionales y de ciclos
|
||||
|
||||
# Perl tiene la mayoría de las estructuras condicionales y de ciclos mas comunes.
|
||||
|
||||
# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes
|
||||
if ( $var ) {
|
||||
...
|
||||
...;
|
||||
} elsif ( $var eq 'bar' ) {
|
||||
...
|
||||
...;
|
||||
} else {
|
||||
...
|
||||
...;
|
||||
}
|
||||
|
||||
unless ( condicion ) {
|
||||
...
|
||||
}
|
||||
# Esto es proporcionado como una version mas fácil de leer que "if (!condición)"
|
||||
...;
|
||||
}
|
||||
|
||||
# La post condición al modo Perl
|
||||
# Esto se ofrece como una versión más fácil de leer que "if (!condición)"
|
||||
|
||||
# La postcondición al modo Perl:
|
||||
print "Yow!" if $zippy;
|
||||
print "No tenemos bananas" unless $bananas;
|
||||
|
||||
# while
|
||||
while ( condicion ) {
|
||||
...
|
||||
}
|
||||
|
||||
while ( condicion ) {
|
||||
...;
|
||||
}
|
||||
|
||||
# for y foreach
|
||||
for ($i = 0; $i <= $max; $i++) {
|
||||
...
|
||||
}
|
||||
...;
|
||||
}
|
||||
|
||||
for $i (0 .. $max) {
|
||||
...;
|
||||
}
|
||||
|
||||
foreach (@array) {
|
||||
print "Este elemento es $_\n";
|
||||
}
|
||||
print "Este elemento es $_\n";
|
||||
}
|
||||
|
||||
|
||||
#### Expresiones regulares
|
||||
|
||||
# El soporte de expresiones regulares en Perl es muy amplio y profundo, y es
|
||||
# sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
|
||||
# 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:
|
||||
|
||||
# Pareo simple
|
||||
# Coincidencia simple
|
||||
if (/foo/) { ... } # verdadero si $_ contiene "foo"
|
||||
if ($a =~ /foo/) { ... } # verdadero si $a contiene "foo"
|
||||
|
||||
# Substitución simple
|
||||
$a =~ s/foo/bar/; # remplaza foo con bar en $a
|
||||
$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de foo con bar en $a
|
||||
$a =~ s/foo/bar/; # remplaza "foo" con "bar" en $a
|
||||
$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en $a
|
||||
|
||||
|
||||
#### Archivos e I/O
|
||||
#### Archivos y E/S
|
||||
|
||||
# Puedes abrir un archivo para obtener datos o escribirlos utilizando la
|
||||
# función "open()".
|
||||
# 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: $!";
|
||||
open(my $salida, ">", "salida.txt") or die "No es posible abrir salida.txt: $!";
|
||||
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 "<>"
|
||||
# operador. En contexto escalar leer una sola linea desde el gestor de
|
||||
# archivo, y en contexto de lista leer el archivo completo en donde, asigna
|
||||
# cada linea a un elemento de la lista.
|
||||
# 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
|
||||
# cada línea a un elemento de la lista
|
||||
|
||||
my $linea = <$entrada>;
|
||||
my @lineas = <$entrada>;
|
||||
@ -131,30 +131,26 @@ my @lineas = <$entrada>;
|
||||
#### Escribiendo subrutinas
|
||||
|
||||
# Escribir subrutinas es fácil:
|
||||
|
||||
sub logger {
|
||||
my $mensajelog = shift;
|
||||
open my $archivolog, ">>", "mi.log" or die "No es posible abrir mi.log: $!";
|
||||
print $archivolog $mensajelog;
|
||||
}
|
||||
|
||||
# Ahora podemos utilizar la subrutina al igual que cualquier otra función
|
||||
# incorporada:
|
||||
|
||||
# Ahora podemos utilizar la subrutina al igual que cualquier otra función incorporada:
|
||||
logger("Tenemos una subrutina logger!");
|
||||
|
||||
|
||||
```
|
||||
|
||||
#### Utilizando módulos Perl
|
||||
|
||||
Los módulos en Perl proveen una gama de funciones que te pueden ayudar a evitar reinventar la rueda, estas pueden ser descargadas desde CPAN( http://www.cpan.org/ ). Algunos de los módulos mas populares ya están incluidos con la misma distribución de Perl.
|
||||
Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde CPAN ( http://www.cpan.org/ ). Algunos de los módulos más populares ya están incluidos con la misma distribución de Perl.
|
||||
|
||||
perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos CPAN para usar.
|
||||
perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos de CPAN que puede usar.
|
||||
|
||||
#### Material de Lectura
|
||||
|
||||
- [perl-tutorial](http://perl-tutorial.org/)
|
||||
- [Aprende en www.perl.com](http://www.perl.org/learn.html)
|
||||
- [Learn Perl](http://www.perl.org/learn.html)
|
||||
- [perldoc](http://perldoc.perl.org/)
|
||||
- y perl incorporado: `perldoc perlintro`
|
||||
- y en su propio perl: `perldoc perlintro`
|
||||
|
@ -336,8 +336,8 @@ class Humain
|
||||
puts "#{msg}"
|
||||
end
|
||||
|
||||
def species
|
||||
@@species
|
||||
def espece
|
||||
@@espece
|
||||
end
|
||||
|
||||
end
|
||||
|
@ -78,7 +78,7 @@ func learnTypes() {
|
||||
can include line breaks.` // Same string type.
|
||||
|
||||
// Non-ASCII literal. Go source is UTF-8.
|
||||
g := 'Σ' // rune type, an alias for uint32, holds a unicode code point.
|
||||
g := 'Σ' // rune type, an alias for int32, holds a unicode code point.
|
||||
|
||||
f := 3.14195 // float64, an IEEE-754 64-bit floating point number.
|
||||
c := 3 + 4i // complex128, represented internally with two float64's.
|
||||
@ -101,6 +101,20 @@ can include line breaks.` // Same string type.
|
||||
var d2 [][]float64 // Declaration only, nothing allocated here.
|
||||
bs := []byte("a slice") // Type conversion syntax.
|
||||
|
||||
// Because they are dynamic, slices can be appended to on-demand.
|
||||
// To append elements to a slice, built-in append() function is used.
|
||||
// First argument is a slice to which we are appending. Commonly,
|
||||
// the array variable is updated in place, as in example below.
|
||||
s := []int{1, 2, 3} // Result is a slice of length 3.
|
||||
s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
|
||||
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
|
||||
// To append another slice, instead of list of atomic elements we can
|
||||
// pass a reference to a slice or a slice literal like this, with a
|
||||
// trailing elipsis, meaning take a slice and unpack its elements,
|
||||
// appending them to slice s.
|
||||
s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal.
|
||||
fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9]
|
||||
|
||||
p, q := learnMemory() // Declares p, q to be type pointer to int.
|
||||
fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
|
||||
|
||||
|
@ -79,7 +79,7 @@ func learnTypes() {
|
||||
개행을 포함할 수 있다.` // 같은 string 타입
|
||||
|
||||
// non-ASCII 리터럴. Go 소스는 UTF-8로 작성해야 한다.
|
||||
g := 'Σ' // 유니코드 코드 포인트를 담고 있고, uint32 타입의 가칭(alias)인 rune 타입
|
||||
g := 'Σ' // 유니코드 코드 포인트를 담고 있고, int32 타입의 가칭(alias)인 rune 타입
|
||||
|
||||
f := 3.14195 // float64, an IEEE-754 64-bit 부동소수 타입
|
||||
c := 3 + 4i // complex128, 내부적으로는 두 개의 float64 타입으로 표현됨
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -75,7 +75,7 @@ func learnTypes() {
|
||||
pode incluir quebras de linha.` // mesmo tipo string
|
||||
|
||||
// literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8.
|
||||
g := 'Σ' // tipo rune, um alias para uint32, que contém um código unicode
|
||||
g := 'Σ' // tipo rune, um alias para int32, que contém um código unicode
|
||||
|
||||
f := 3.14195 // float64, número de vírgula flutuante de 64bit (IEEE-754)
|
||||
c := 3 + 4i // complex128, representado internamente com dois float64s
|
||||
|
@ -93,7 +93,9 @@ not False # => True
|
||||
"{} can be {}".format("strings", "interpolated")
|
||||
|
||||
# You can repeat the formatting arguments to save some typing.
|
||||
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") #=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
|
||||
"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
|
||||
#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
|
||||
|
||||
# You can use keywords if you don't want to count.
|
||||
"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
|
||||
|
||||
|
@ -79,7 +79,7 @@ func learnTypes() {
|
||||
может содержать переносы строк` // Тоже тип данных string
|
||||
|
||||
// Символ не из ASCII. Исходный код Go в кодировке UTF-8.
|
||||
g := 'Σ' // тип rune, это алиас для типа uint32, содержит символ юникода.
|
||||
g := 'Σ' // тип rune, это алиас для типа int32, содержит символ юникода.
|
||||
|
||||
f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754).
|
||||
c := 3 + 4i // complex128, внутри себя содержит два float64.
|
||||
|
@ -243,7 +243,7 @@ i // Show the value of i. Note that while is a loop in the classical sense -
|
||||
|
||||
// A do while loop
|
||||
do {
|
||||
println("x is still less then 10");
|
||||
println("x is still less than 10");
|
||||
x += 1
|
||||
} while (x < 10)
|
||||
|
||||
@ -299,7 +299,6 @@ Person("George", "1234") == Person("Kate", "1236")
|
||||
|
||||
|
||||
|
||||
|
||||
// Pattern matching
|
||||
|
||||
val me = Person("George", "1234")
|
||||
@ -322,15 +321,21 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy"
|
||||
|
||||
|
||||
// Regular expressions
|
||||
|
||||
val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex
|
||||
val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax
|
||||
|
||||
val email(user, domain) = "henry@zkpr.com"
|
||||
|
||||
"mrbean@pyahoo.com" match {
|
||||
case email(name, domain) => "I know your name, " + name
|
||||
val matcher = (value: String) => {
|
||||
println(value match {
|
||||
case email(name, domain) => s"It was an email: $name"
|
||||
case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4"
|
||||
case _ => s"No match on '$value'" // default if no match found
|
||||
})
|
||||
}
|
||||
|
||||
matcher("mrbean@pyahoo.com") // => "It was an email: mrbean"
|
||||
matcher("nope..") // => "No match on 'nope..'"
|
||||
matcher("52917") // => "No match on '52917'"
|
||||
matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917"
|
||||
|
||||
|
||||
// Strings
|
||||
@ -347,17 +352,27 @@ println("ABCDEF".length)
|
||||
println("ABCDEF".substring(2, 6))
|
||||
println("ABCDEF".replace("C", "3"))
|
||||
|
||||
// String interpolation
|
||||
val n = 45
|
||||
println(s"We have $n apples")
|
||||
println(s"We have $n apples") // => "We have 45 apples"
|
||||
|
||||
// Expressions inside interpolated strings are also possible
|
||||
val a = Array(11, 9, 6)
|
||||
println(s"My second daughter is ${a(2-1)} years old")
|
||||
println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old."
|
||||
println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples."
|
||||
println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4"
|
||||
|
||||
// Formatting with interpolated strings (note the prefixed f)
|
||||
println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25"
|
||||
println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122"
|
||||
|
||||
// Ignoring special characters.
|
||||
println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r."
|
||||
|
||||
// Some characters need to be 'escaped', e.g. a double quote inside a string:
|
||||
val a = "They stood outside the \"Rose and Crown\""
|
||||
val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
|
||||
|
||||
// Triple double-quotes let strings span multiple rows and contain quotes
|
||||
|
||||
val html = """<form id="daform">
|
||||
<p>Press belo', Joe</p>
|
||||
| <input type="submit">
|
||||
@ -403,7 +418,10 @@ for(line <- Source.fromFile("myfile.txt").getLines())
|
||||
println(line)
|
||||
|
||||
// To write a file use Java's PrintWriter
|
||||
|
||||
val writer = new PrintWriter("myfile.txt")
|
||||
writer.write("Writing line for line" + util.Properties.lineSeparator)
|
||||
writer.write("Another line here" + util.Properties.lineSeparator)
|
||||
writer.close()
|
||||
|
||||
```
|
||||
|
||||
|
@ -39,7 +39,7 @@ var occupations = [
|
||||
"kaylee": "Mechanic"
|
||||
]
|
||||
occupations["Jayne"] = "Public Relations"
|
||||
let emptyDictionary = Dictionary<String, Float>()
|
||||
let emptyDictionary = [String: Float]()
|
||||
|
||||
|
||||
//
|
||||
|
@ -68,7 +68,7 @@ func learnTypes() {
|
||||
can include line breaks.` // 同样是String类型
|
||||
|
||||
// 非ascii字符。Go使用UTF-8编码。
|
||||
g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码
|
||||
g := 'Σ' // rune类型,int32的别名,使用UTF-8编码
|
||||
|
||||
f := 3.14195 // float64类型,IEEE-754 64位浮点数
|
||||
c := 3 + 4i // complex128类型,内部使用两个float64表示
|
||||
|
Loading…
Reference in New Issue
Block a user