mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-04-27 07:33:57 +00:00
Merge branch 'master' of https://github.com/adambard/learnxinyminutes-docs into docker-docs
This commit is contained in:
commit
66acfb83d1
@ -118,12 +118,12 @@ BEGIN {
|
||||
# Arrays
|
||||
arr[0] = "foo";
|
||||
arr[1] = "bar";
|
||||
|
||||
|
||||
# You can also initialize an array with the built-in function split()
|
||||
|
||||
|
||||
n = split("foo:bar:baz", arr, ":");
|
||||
|
||||
# You also have associative arrays (actually, they're all associative arrays)
|
||||
|
||||
# You also have associative arrays (indeed, they're all associative arrays)
|
||||
assoc["foo"] = "bar";
|
||||
assoc["bar"] = "baz";
|
||||
|
||||
@ -216,7 +216,8 @@ function string_functions( localvar, arr) {
|
||||
match(localvar, "t"); # => 4, since the 't' is the fourth character
|
||||
|
||||
# Split on a delimiter
|
||||
n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
|
||||
n = split("foo-bar-baz", arr, "-");
|
||||
# result: a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
|
||||
|
||||
# Other useful stuff
|
||||
sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3"
|
||||
@ -238,9 +239,9 @@ function io_functions( localvar) {
|
||||
# AWK doesn't have file handles, per se. It will automatically open a file
|
||||
# handle for you when you use something that needs one. The string you used
|
||||
# for this can be treated as a file handle, for purposes of I/O. This makes
|
||||
# it feel sort of like shell scripting, but to get the same output, the string
|
||||
# must match exactly, so use a variable:
|
||||
|
||||
# it feel sort of like shell scripting, but to get the same output, the
|
||||
# string must match exactly, so use a variable:
|
||||
|
||||
outfile = "/tmp/foobar.txt";
|
||||
|
||||
print "foobar" > outfile;
|
||||
@ -261,7 +262,7 @@ function io_functions( localvar) {
|
||||
|
||||
# Reads a line from a file and stores in localvar
|
||||
infile = "/tmp/foobar.txt";
|
||||
getline localvar < infile;
|
||||
getline localvar < infile;
|
||||
close(infile);
|
||||
}
|
||||
|
||||
@ -273,10 +274,10 @@ function io_functions( localvar) {
|
||||
# When you pass arguments to AWK, they are treated as file names to process.
|
||||
# It will process them all, in order. Think of it like an implicit for loop,
|
||||
# iterating over the lines in these files. these patterns and actions are like
|
||||
# switch statements inside the loop.
|
||||
# switch statements inside the loop.
|
||||
|
||||
/^fo+bar$/ {
|
||||
|
||||
|
||||
# This action will execute for every line that matches the regular
|
||||
# expression, /^fo+bar$/, and will be skipped for any line that fails to
|
||||
# match it. Let's just print the line:
|
||||
@ -376,11 +377,15 @@ END {
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Further Reading:
|
||||
|
||||
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
|
||||
* [Awk man page](https://linux.die.net/man/1/awk)
|
||||
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems.
|
||||
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html)
|
||||
GNU Awk is found on most Linux systems.
|
||||
* [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html)
|
||||
* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical summary and list of "gotchas" (places where different implementations may behave in different or unexpected ways).
|
||||
* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical
|
||||
summary and list of "gotchas" (places where different implementations may
|
||||
behave in different or unexpected ways).
|
||||
* [basic libraries for awk](https://github.com/dubiousjim/awkenough)
|
||||
|
@ -18,6 +18,7 @@ contributors:
|
||||
- ["Harry Mumford-Turner", "https://github.com/harrymt"]
|
||||
- ["Martin Nicholson", "https://github.com/mn113"]
|
||||
- ["Mark Grimwood", "https://github.com/MarkGrimwood"]
|
||||
- ["Emily Grace Seville", "https://github.com/EmilySeville7cfg"]
|
||||
filename: LearnBash.sh
|
||||
translators:
|
||||
- ["Dimitri Kokkonis", "https://github.com/kokkonisd"]
|
||||
@ -37,104 +38,107 @@ or executed directly in the shell.
|
||||
# As you already figured, comments start with #. Shebang is also a comment.
|
||||
|
||||
# Simple hello world example:
|
||||
echo Hello world! # => Hello world!
|
||||
echo "Hello world!" # => Hello world!
|
||||
|
||||
# Each command starts on a new line, or after a semicolon:
|
||||
echo 'This is the first line'; echo 'This is the second line'
|
||||
# => This is the first line
|
||||
# => This is the second line
|
||||
echo "This is the first command"; echo "This is the second command"
|
||||
# => This is the first command
|
||||
# => This is the second command
|
||||
|
||||
# Declaring a variable looks like this:
|
||||
Variable="Some string"
|
||||
variable="Some string"
|
||||
|
||||
# But not like this:
|
||||
Variable = "Some string" # => returns error "Variable: command not found"
|
||||
# Bash will decide that Variable is a command it must execute and give an error
|
||||
variable = "Some string" # => returns error "variable: command not found"
|
||||
# Bash will decide that `variable` is a command it must execute and give an error
|
||||
# because it can't be found.
|
||||
|
||||
# Nor like this:
|
||||
Variable= 'Some string' # => returns error: "Some string: command not found"
|
||||
# Bash will decide that 'Some string' is a command it must execute and give an
|
||||
# error because it can't be found. (In this case the 'Variable=' part is seen
|
||||
# as a variable assignment valid only for the scope of the 'Some string'
|
||||
# command.)
|
||||
variable= "Some string" # => returns error: "Some string: command not found"
|
||||
# Bash will decide that "Some string" is a command it must execute and give an
|
||||
# error because it can't be found. In this case the "variable=" part is seen
|
||||
# as a variable assignment valid only for the scope of the "Some string"
|
||||
# command.
|
||||
|
||||
# Using the variable:
|
||||
echo $Variable # => Some string
|
||||
echo "$Variable" # => Some string
|
||||
echo '$Variable' # => $Variable
|
||||
# When you use the variable itself — assign it, export it, or else — you write
|
||||
echo "$variable" # => Some string
|
||||
echo '$variable' # => $variable
|
||||
# When you use a variable itself — assign it, export it, or else — you write
|
||||
# its name without $. If you want to use the variable's value, you should use $.
|
||||
# Note that ' (single quote) won't expand the variables!
|
||||
# You can write variable without surrounding quotes but it's not recommended.
|
||||
|
||||
# Parameter expansion ${ }:
|
||||
echo ${Variable} # => Some string
|
||||
# This is a simple usage of parameter expansion
|
||||
# Parameter Expansion gets a value from a variable.
|
||||
# It "expands" or prints the value
|
||||
# During the expansion time the value or parameter can be modified
|
||||
# Below are other modifications that add onto this expansion
|
||||
# Parameter expansion ${...}:
|
||||
echo "${variable}" # => Some string
|
||||
# This is a simple usage of parameter expansion such as two examples above.
|
||||
# Parameter expansion gets a value from a variable.
|
||||
# It "expands" or prints the value.
|
||||
# During the expansion time the value or parameter can be modified.
|
||||
# Below are other modifications that add onto this expansion.
|
||||
|
||||
# String substitution in variables
|
||||
echo ${Variable/Some/A} # => A string
|
||||
# This will substitute the first occurrence of "Some" with "A"
|
||||
# String substitution in variables:
|
||||
echo "${variable/Some/A}" # => A string
|
||||
# This will substitute the first occurrence of "Some" with "A".
|
||||
|
||||
# Substring from a variable
|
||||
Length=7
|
||||
echo ${Variable:0:Length} # => Some st
|
||||
# Substring from a variable:
|
||||
length=7
|
||||
echo "${variable:0:length}" # => Some st
|
||||
# This will return only the first 7 characters of the value
|
||||
echo ${Variable: -5} # => tring
|
||||
# This will return the last 5 characters (note the space before -5)
|
||||
echo "${variable: -5}" # => tring
|
||||
# This will return the last 5 characters (note the space before -5).
|
||||
# The space before minus is mandatory here.
|
||||
|
||||
# String length
|
||||
echo ${#Variable} # => 11
|
||||
# String length:
|
||||
echo "${#variable}" # => 11
|
||||
|
||||
# Indirect expansion
|
||||
OtherVariable="Variable"
|
||||
echo ${!OtherVariable} # => Some String
|
||||
# This will expand the value of OtherVariable
|
||||
# Indirect expansion:
|
||||
other_variable="variable"
|
||||
echo ${!other_variable} # => Some string
|
||||
# This will expand the value of `other_variable`.
|
||||
|
||||
# Default value for variable
|
||||
echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
|
||||
# The default value for variable:
|
||||
echo "${foo:-"DefaultValueIfFooIsMissingOrEmpty"}"
|
||||
# => DefaultValueIfFooIsMissingOrEmpty
|
||||
# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
|
||||
# This works for null (foo=) and empty string (foo=""); zero (foo=0) returns 0.
|
||||
# Note that it only returns default value and doesn't change variable value.
|
||||
|
||||
# Declare an array with 6 elements
|
||||
array0=(one two three four five six)
|
||||
# Print first element
|
||||
echo $array0 # => "one"
|
||||
# Print first element
|
||||
echo ${array0[0]} # => "one"
|
||||
# Print all elements
|
||||
echo ${array0[@]} # => "one two three four five six"
|
||||
# Print number of elements
|
||||
echo ${#array0[@]} # => "6"
|
||||
# Print number of characters in third element
|
||||
echo ${#array0[2]} # => "5"
|
||||
# Print 2 elements starting from fourth
|
||||
echo ${array0[@]:3:2} # => "four five"
|
||||
# Print all elements. Each of them on new line.
|
||||
for i in "${array0[@]}"; do
|
||||
echo "$i"
|
||||
# Declare an array with 6 elements:
|
||||
array=(one two three four five six)
|
||||
# Print the first element:
|
||||
echo "${array[0]}" # => "one"
|
||||
# Print all elements:
|
||||
echo "${array[@]}" # => "one two three four five six"
|
||||
# Print the number of elements:
|
||||
echo "${#array[@]}" # => "6"
|
||||
# Print the number of characters in third element
|
||||
echo "${#array[2]}" # => "5"
|
||||
# Print 2 elements starting from fourth:
|
||||
echo "${array[@]:3:2}" # => "four five"
|
||||
# Print all elements each of them on new line.
|
||||
for item in "${array[@]}"; do
|
||||
echo "$item"
|
||||
done
|
||||
|
||||
# Brace Expansion { }
|
||||
# Used to generate arbitrary strings
|
||||
echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
|
||||
echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z
|
||||
# This will output the range from the start value to the end value
|
||||
|
||||
# Built-in variables:
|
||||
# There are some useful built-in variables, like
|
||||
# There are some useful built-in variables, like:
|
||||
echo "Last program's return value: $?"
|
||||
echo "Script's PID: $$"
|
||||
echo "Number of arguments passed to script: $#"
|
||||
echo "All arguments passed to script: $@"
|
||||
echo "Script's arguments separated into different variables: $1 $2..."
|
||||
|
||||
# Brace Expansion {...}
|
||||
# used to generate arbitrary strings:
|
||||
echo {1..10} # => 1 2 3 4 5 6 7 8 9 10
|
||||
echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z
|
||||
# This will output the range from the start value to the end value.
|
||||
# Note that you can't use variables here:
|
||||
from=1
|
||||
to=10
|
||||
echo {$from..$to} # => {$from..$to}
|
||||
|
||||
# Now that we know how to echo and use variables,
|
||||
# let's learn some of the other basics of bash!
|
||||
# let's learn some of the other basics of Bash!
|
||||
|
||||
# Our current directory is available through the command `pwd`.
|
||||
# `pwd` stands for "print working directory".
|
||||
@ -144,33 +148,46 @@ echo "I'm in $(pwd)" # execs `pwd` and interpolates output
|
||||
echo "I'm in $PWD" # interpolates the variable
|
||||
|
||||
# If you get too much output in your terminal, or from a script, the command
|
||||
# `clear` clears your screen
|
||||
# `clear` clears your screen:
|
||||
clear
|
||||
# Ctrl-L also works for clearing output
|
||||
# Ctrl-L also works for clearing output.
|
||||
|
||||
# Reading a value from input:
|
||||
echo "What's your name?"
|
||||
read Name # Note that we didn't need to declare a new variable
|
||||
echo Hello, $Name!
|
||||
read name
|
||||
# Note that we didn't need to declare a new variable.
|
||||
echo "Hello, $name!"
|
||||
|
||||
# We have the usual if structure:
|
||||
# use `man test` for more info about conditionals
|
||||
if [ $Name != $USER ]
|
||||
then
|
||||
# We have the usual if structure.
|
||||
# Condition is true if the value of $name is not equal to the current user's login username:
|
||||
if [[ "$name" != "$USER" ]]; then
|
||||
echo "Your name isn't your username"
|
||||
else
|
||||
echo "Your name is your username"
|
||||
fi
|
||||
# True if the value of $Name is not equal to the current user's login username
|
||||
|
||||
# NOTE: if $Name is empty, bash sees the above condition as:
|
||||
if [ != $USER ]
|
||||
# which is invalid syntax
|
||||
# so the "safe" way to use potentially empty variables in bash is:
|
||||
if [ "$Name" != $USER ] ...
|
||||
# which, when $Name is empty, is seen by bash as:
|
||||
if [ "" != $USER ] ...
|
||||
# which works as expected
|
||||
# To use && and || with if statements, you need multiple pairs of square brackets:
|
||||
read age
|
||||
if [[ "$name" == "Steve" ]] && [[ "$age" -eq 15 ]]; then
|
||||
echo "This will run if $name is Steve AND $age is 15."
|
||||
fi
|
||||
|
||||
if [[ "$name" == "Daniya" ]] || [[ "$name" == "Zach" ]]; then
|
||||
echo "This will run if $name is Daniya OR Zach."
|
||||
fi
|
||||
# There are other comparison operators for numbers listed below:
|
||||
# -ne - not equal
|
||||
# -lt - less than
|
||||
# -gt - greater than
|
||||
# -le - less than or equal to
|
||||
# -ge - greater than or equal to
|
||||
|
||||
# There is also the `=~` operator, which tests a string against the Regex pattern:
|
||||
email=me@example.com
|
||||
if [[ "$email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]]
|
||||
then
|
||||
echo "Valid email!"
|
||||
fi
|
||||
|
||||
# There is also conditional execution
|
||||
echo "Always executed" || echo "Only executed if first command fails"
|
||||
@ -193,27 +210,6 @@ bg
|
||||
kill %2
|
||||
# %1, %2, etc. can be used for fg and bg as well
|
||||
|
||||
# To use && and || with if statements, you need multiple pairs of square brackets:
|
||||
if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ]
|
||||
then
|
||||
echo "This will run if $Name is Steve AND $Age is 15."
|
||||
fi
|
||||
|
||||
if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ]
|
||||
then
|
||||
echo "This will run if $Name is Daniya OR Zach."
|
||||
fi
|
||||
|
||||
# There is also the `=~` operator, which tests a string against a Regex pattern:
|
||||
Email=me@example.com
|
||||
if [[ "$Email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]]
|
||||
then
|
||||
echo "Valid email!"
|
||||
fi
|
||||
# Note that =~ only works within double [[ ]] square brackets,
|
||||
# which are subtly different from single [ ].
|
||||
# See https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs for more on this.
|
||||
|
||||
# Redefine command `ping` as alias to send only 5 packets
|
||||
alias ping='ping -c 5'
|
||||
# Escape the alias and use command with this name instead
|
||||
|
@ -2,15 +2,15 @@
|
||||
language: C
|
||||
filename: learnc.c
|
||||
contributors:
|
||||
- ["Adam Bard", "http://adambard.com/"]
|
||||
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
|
||||
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
|
||||
- ["Marco Scannadinari", "https://marcoms.github.io"]
|
||||
- ["Zachary Ferguson", "https://github.io/zfergus2"]
|
||||
- ["himanshu", "https://github.com/himanshu81494"]
|
||||
- ["Joshua Li", "https://github.com/JoshuaRLi"]
|
||||
- ["Dragos B. Chirila", "https://github.com/dchirila"]
|
||||
- ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"]
|
||||
- ["Adam Bard", "http://adambard.com/"]
|
||||
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
|
||||
- ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
|
||||
- ["Marco Scannadinari", "https://marcoms.github.io"]
|
||||
- ["Zachary Ferguson", "https://github.io/zfergus2"]
|
||||
- ["himanshu", "https://github.com/himanshu81494"]
|
||||
- ["Joshua Li", "https://github.com/JoshuaRLi"]
|
||||
- ["Dragos B. Chirila", "https://github.com/dchirila"]
|
||||
- ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"]
|
||||
---
|
||||
|
||||
Ah, C. Still **the** language of modern high-performance computing.
|
||||
@ -101,6 +101,12 @@ int main (int argc, char** argv)
|
||||
// %d is an integer, \n is a newline
|
||||
printf("%d\n", 0); // => Prints 0
|
||||
|
||||
// take input using scanf
|
||||
// '&' is used to define the location
|
||||
// where we want to store the input value
|
||||
int input;
|
||||
scanf("%d", &input);
|
||||
|
||||
///////////////////////////////////////
|
||||
// Types
|
||||
///////////////////////////////////////
|
||||
@ -118,7 +124,7 @@ int main (int argc, char** argv)
|
||||
// shorts are usually 2 bytes (use the `sizeof` operator to check)
|
||||
short x_short = 0;
|
||||
|
||||
// chars are defined as the smallest addressable unit for a processor.
|
||||
// chars are defined as the smallest addressable unit for a processor.
|
||||
// This is usually 1 byte, but for some systems it can be more (ex. for TMS320 from TI it's 2 bytes).
|
||||
char x_char = 0;
|
||||
char y_char = 'y'; // Char literals are quoted with ''
|
||||
@ -167,19 +173,19 @@ int main (int argc, char** argv)
|
||||
// where the "{0}" part is called an "array initializer".
|
||||
// All elements (if any) past the ones in the initializer are initialized to 0:
|
||||
int my_array[5] = {1, 2};
|
||||
// So my_array now has five elements, all but the first two of which are 0:
|
||||
// So my_array now has five elements, all but the first two of which are 0:
|
||||
// [1, 2, 0, 0, 0]
|
||||
// NOTE that you get away without explicitly declaring the size
|
||||
// NOTE that you get away without explicitly declaring the size
|
||||
// of the array IF you initialize the array on the same line:
|
||||
int my_array[] = {0};
|
||||
// NOTE that, when not declaring the size, the size of the array is the number
|
||||
// NOTE that, when not declaring the size, the size of the array is the number
|
||||
// of elements in the initializer. With "{0}", my_array is now of size one: [0]
|
||||
// To evaluate the size of the array at run-time, divide its byte size by the
|
||||
// byte size of its element type:
|
||||
size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]);
|
||||
// WARNING You should evaluate the size *before* you begin passing the array
|
||||
// to functions (see later discussion) because arrays get "downgraded" to
|
||||
// raw pointers when they are passed to functions (so the statement above
|
||||
// WARNING You should evaluate the size *before* you begin passing the array
|
||||
// to functions (see later discussion) because arrays get "downgraded" to
|
||||
// raw pointers when they are passed to functions (so the statement above
|
||||
// will produce the wrong result inside the function).
|
||||
|
||||
// Indexing an array is like other languages -- or,
|
||||
@ -247,11 +253,11 @@ int main (int argc, char** argv)
|
||||
(float)i1 / i2; // => 0.5f
|
||||
i1 / (double)i2; // => 0.5 // Same with double
|
||||
f1 / f2; // => 0.5, plus or minus epsilon
|
||||
|
||||
|
||||
// Floating-point numbers are defined by IEEE 754, thus cannot store perfectly
|
||||
// exact values. For instance, the following does not produce expected results
|
||||
// because 0.1 might actually be 0.099999999999 insided the computer, and 0.3
|
||||
// might be stored as 0.300000000001.
|
||||
// exact values. For instance, the following does not produce expected results
|
||||
// because 0.1 might actually be 0.099999999999 insided the computer, and 0.3
|
||||
// might be stored as 0.300000000001.
|
||||
(0.1 + 0.1 + 0.1) != 0.3; // => 1 (true)
|
||||
// and it is NOT associative due to reasons mentioned above.
|
||||
1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (true)
|
||||
@ -262,7 +268,7 @@ int main (int argc, char** argv)
|
||||
// eventually calls C which uses IEEE 754. It is mentioned this way not to
|
||||
// indicate that this is a poor implementation, but instead as a warning
|
||||
// that when doing floating point comparisons, a little bit of error (epsilon)
|
||||
// needs to be considered.
|
||||
// needs to be considered.
|
||||
|
||||
// Modulo is there as well, but be careful if arguments are negative
|
||||
11 % 3; // => 2 as 11 = 2 + 3*x (x=3)
|
||||
@ -411,7 +417,7 @@ int main (int argc, char** argv)
|
||||
*/
|
||||
/*
|
||||
it is generally considered bad practice to do so, except if
|
||||
you really know what you are doing. See
|
||||
you really know what you are doing. See
|
||||
https://en.wikipedia.org/wiki/Spaghetti_code#Meaning
|
||||
*/
|
||||
|
||||
@ -424,7 +430,7 @@ int main (int argc, char** argv)
|
||||
|
||||
int x_hex = 0x01; // You can assign vars with hex literals
|
||||
// binary is not in the standard, but allowed by some
|
||||
// compilers (x_bin = 0b0010010110)
|
||||
// compilers (x_bin = 0b0010010110)
|
||||
|
||||
// Casting between types will attempt to preserve their numeric values
|
||||
printf("%d\n", x_hex); // => Prints 1
|
||||
@ -626,7 +632,7 @@ printf("first: %d\nsecond: %d\n", first, second);
|
||||
// values will be swapped
|
||||
*/
|
||||
|
||||
// Return multiple values.
|
||||
// Return multiple values.
|
||||
// C does not allow for returning multiple values with the return statement. If
|
||||
// you would like to return multiple values, then the caller must pass in the
|
||||
// variables where they would like the returned values to go. These variables must
|
||||
@ -637,9 +643,9 @@ int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3)
|
||||
return 0; //return error code (false)
|
||||
|
||||
//de-reference the pointer so we modify its value
|
||||
*ret1 = array_of_3[0];
|
||||
*ret2 = array_of_3[1];
|
||||
*ret3 = array_of_3[2];
|
||||
*ret1 = array_of_3[0];
|
||||
*ret2 = array_of_3[1];
|
||||
*ret3 = array_of_3[2];
|
||||
|
||||
return 1; //return error code (true)
|
||||
}
|
||||
@ -901,10 +907,11 @@ Node createLinkedList(int *vals, int len);
|
||||
#endif /* End of the if precompiler directive. */
|
||||
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
||||
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
|
||||
It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
|
||||
It is _the_ book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
|
||||
inaccuracies (well, ideas that are not considered good anymore) or now-changed practices.
|
||||
|
||||
Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/) (not free).
|
||||
|
@ -132,7 +132,7 @@ organizations.
|
||||
|
||||
*Now it is time to learn about two related COBOL verbs: string and unstring.
|
||||
|
||||
*The string verb is used to concatenate, or put together, two or more stings.
|
||||
*The string verb is used to concatenate, or put together, two or more strings.
|
||||
*Unstring is used, not surprisingly, to separate a
|
||||
*string into two or more smaller strings.
|
||||
*It is important that you remember to use ‘delimited by’ when you
|
||||
|
@ -3,94 +3,92 @@ category: tool
|
||||
tool: vim
|
||||
lang: de-de
|
||||
contributors:
|
||||
- ["RadhikaG", "https://github.com/RadhikaG"]
|
||||
- ["RadhikaG", "https://github.com/RadhikaG"]
|
||||
translators:
|
||||
- ["caminsha", "https://github.com/caminsha"]
|
||||
- ["caminsha", "https://github.com/caminsha"]
|
||||
filename: LearnVim-de.txt
|
||||
---
|
||||
|
||||
|
||||
[Vim](http://www.vim.org)
|
||||
(Vi IMproved) ist ein Klon von vi, dem bekannten Editor für Unix. Es ist ein
|
||||
Texteditor, welcher mit Fokus auf Geschwindigkeit und Prouktivität entwickelt
|
||||
wurde.
|
||||
Vim hat viele Keybindings für ein schnelles navigieren und schnelles bearbeiten
|
||||
einer Datei.
|
||||
Texteditor, welcher mit Fokus auf Geschwindigkeit und Produktivität entwickelt
|
||||
wurde. Vim hat viele Keybindings für ein schnelles navigieren und schnelles
|
||||
bearbeiten einer Datei.
|
||||
|
||||
## Grundlagen, um in Vim zu navigieren
|
||||
|
||||
```
|
||||
vim <filename> # Öffne <filename> in Vim
|
||||
:help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn
|
||||
# es existiert
|
||||
:q # Schließe vim
|
||||
:w # Speichere diese Datei
|
||||
:wq # Speichere diese Datei und schließe vim
|
||||
ZZ # Speichere diese Datei und schließe vim
|
||||
:q! # Schließe vim ohne die Datei zu speichern
|
||||
# ! *zwingt* die Ausführung von :q,
|
||||
# daher wird die Datei nicht gespeichert.
|
||||
ZQ # Beende vim ohne die Datei zu speichern
|
||||
:x # Speichere die Datei und beende vim
|
||||
# Dies ist eine kürzere Version von :wq
|
||||
vim <filename> # Öffne <filename> in Vim
|
||||
:help <topic> # Öffne die eingebaute Hilfe zum Thema <topic>, wenn
|
||||
# es existiert
|
||||
:q # Schließe vim
|
||||
:w # Speichere diese Datei
|
||||
:wq # Speichere diese Datei und schließe vim
|
||||
ZZ # Speichere diese Datei und schließe vim
|
||||
:q! # Schließe vim ohne die Datei zu speichern
|
||||
# ! *zwingt* die Ausführung von :q,
|
||||
# daher wird die Datei nicht gespeichert.
|
||||
ZQ # Beende vim ohne die Datei zu speichern
|
||||
:x # Speichere die Datei und beende vim
|
||||
# Dies ist eine kürzere Version von :wq
|
||||
|
||||
u # Änderung rückgängig machen
|
||||
CTRL+R # Änderung wiederherstellen
|
||||
u # Änderung rückgängig machen
|
||||
CTRL+R # Änderung wiederherstellen
|
||||
|
||||
h # Den Cursor um ein Zeichen nach links bewegen
|
||||
j # Den Cursor eine Zeile nach unten bewegen
|
||||
k # Den Cursor eine Zeile nach oben bewegen
|
||||
l # Den Cursor um ein Zeichen nach rechts bewegen
|
||||
h # Den Cursor um ein Zeichen nach links bewegen
|
||||
j # Den Cursor eine Zeile nach unten bewegen
|
||||
k # Den Cursor eine Zeile nach oben bewegen
|
||||
l # Den Cursor um ein Zeichen nach rechts bewegen
|
||||
|
||||
Ctrl+B # Gehe eine Bildschirmanzeige zurück
|
||||
Ctrl+F # Gehe eine Bildschirmanzeige vorwärts
|
||||
Ctrl+D # Gehe eine halbe Bildschirmanzeige vorwärts
|
||||
Ctrl+U # Gehe eine halbe Bildschirmanzeige zurück
|
||||
Ctrl+B # Gehe eine Bildschirmanzeige zurück
|
||||
Ctrl+F # Gehe eine Bildschirmanzeige vorwärts
|
||||
Ctrl+D # Gehe eine halbe Bildschirmanzeige vorwärts
|
||||
Ctrl+U # Gehe eine halbe Bildschirmanzeige zurück
|
||||
|
||||
# Navigieren innerhalb einer Zeile
|
||||
# Navigieren innerhalb einer Zeile
|
||||
|
||||
0 # Navigiere zum Anfang der Zeile
|
||||
$ # Navigiere zum Ende der Zeile
|
||||
^ # Navigiere zum ersten Zeichen, welches kein Leerzeichen ist
|
||||
0 # Navigiere zum Anfang der Zeile
|
||||
$ # Navigiere zum Ende der Zeile
|
||||
^ # Navigiere zum ersten Zeichen, welches kein Leerzeichen ist
|
||||
|
||||
# Im Text suchen
|
||||
# Im Text suchen
|
||||
|
||||
/word # Hebt alle Ergebnisse nach dem Cursor hervor
|
||||
?word # Hebt alle Ergebnisse vor dem Cursor hervor
|
||||
n # Bewegt den Cursor zum nächsten Ergebnis nach der Suche
|
||||
N # Bewegt den Cursor zum vorherigen Ergebnis der Suche
|
||||
/word # Hebt alle Ergebnisse nach dem Cursor hervor
|
||||
?word # Hebt alle Ergebnisse vor dem Cursor hervor
|
||||
n # Bewegt den Cursor zum nächsten Ergebnis nach der Suche
|
||||
N # Bewegt den Cursor zum vorherigen Ergebnis der Suche
|
||||
|
||||
:%s/foo/bar/g # Ersetze "foo" durch "bar" in allen Zeilen
|
||||
:s/foo/bar/g # Ersetze "foo" durch "bar" in der aktuellen Zeile
|
||||
:%s/\n/\r/g # Ersetze das newline-Zeichen bei allen Zeilen durch
|
||||
# ein carriage return
|
||||
:%s/foo/bar/g # Ersetze "foo" durch "bar" in allen Zeilen
|
||||
:s/foo/bar/g # Ersetze "foo" durch "bar" in der aktuellen Zeile
|
||||
:%s/\n/\r/g # Ersetze das newline-Zeichen bei allen Zeilen durch
|
||||
# ein carriage return
|
||||
|
||||
# Zu einzelnen Zeichen springen
|
||||
# Zu einzelnen Zeichen springen
|
||||
|
||||
f<character> # Springe vorwärts und auf dem Zeichen <character>
|
||||
t<character> # Springe vorwärts und lande vor dem Zeichen <character>
|
||||
f<character> # Springe vorwärts und auf dem Zeichen <character>
|
||||
t<character> # Springe vorwärts und lande vor dem Zeichen <character>
|
||||
|
||||
# Zum Beispiel,
|
||||
f< # Springe vorwärts und lande auf <
|
||||
t< # Springe vorwärts und lande vor <
|
||||
# Zum Beispiel,
|
||||
f< # Springe vorwärts und lande auf <
|
||||
t< # Springe vorwärts und lande vor <
|
||||
|
||||
# Wortweise navigieren
|
||||
# Wortweise navigieren
|
||||
|
||||
w # Springe um ein Wort vorwärts
|
||||
b # Gehe ein Wort zurück
|
||||
e # Springe zum Ende des aktuellen Wortes
|
||||
w # Springe um ein Wort vorwärts
|
||||
b # Gehe ein Wort zurück
|
||||
e # Springe zum Ende des aktuellen Wortes
|
||||
|
||||
# Weitere Befehle, um zu navigieren
|
||||
# Weitere Befehle, um zu navigieren
|
||||
|
||||
gg # Gehe an den Start der Datei
|
||||
G # Gehe an das Ende der Datei
|
||||
:NUM # Springe zur Zeile NUM (NUM kann eine beliebige Zahl sein)
|
||||
H # Navigiere zum Start der aktuellen Bildschirmanzeige
|
||||
M # Navigiere in die Mitte der aktuellen Bildschirmanzeige
|
||||
L # Navigiere an das Ende der aktuellen Bildschirmanzeige
|
||||
gg # Gehe an den Start der Datei
|
||||
G # Gehe an das Ende der Datei
|
||||
:NUM # Springe zur Zeile NUM (NUM kann eine beliebige Zahl sein)
|
||||
H # Navigiere zum Start der aktuellen Bildschirmanzeige
|
||||
M # Navigiere in die Mitte der aktuellen Bildschirmanzeige
|
||||
L # Navigiere an das Ende der aktuellen Bildschirmanzeige
|
||||
```
|
||||
|
||||
## Hilfsdokumente:
|
||||
## Hilfsdokumente
|
||||
|
||||
Vim hat eine eingebaute Dokumentation, welche mit `:help <topic>` aufgerufen
|
||||
werden kann.
|
||||
@ -98,34 +96,33 @@ Zum Beispiel öffnet `:help navigation` die Dokumentation über das Navigieren
|
||||
|
||||
`:help` kann auch ohne ein Argument verwendet werden. Dies zeigt den Standard-
|
||||
Hilfsdialog an, welcher den Start mit vim einfacher macht.
|
||||
that aims to make getting started with vim more approachable!
|
||||
|
||||
## Modi:
|
||||
## Modi
|
||||
|
||||
Vim basiert auf dem Konzept von **modes**.
|
||||
|
||||
- Command Mode - Vim startet in diesem Modus, hier kann man navigieren und Befehle eingeben
|
||||
- Command Mode - Vims erster Modus, hier kann man navigieren und Befehle eingeben
|
||||
- Insert Mode - Wird verwendet, um Änderungen in der Datei zu machen.
|
||||
- Visual Mode - Wird verwendet, um Text zu markieren und Operationen durchzuführen
|
||||
- Visual Mode - Wird verwendet, um Text zu markieren und diesen zu verändern
|
||||
- Ex Mode - Wird verwendet, um im ':'-Prompt Befehle einzugeben
|
||||
|
||||
```
|
||||
i # Führt vim in den Insert Mode, vor der Cursorposition
|
||||
a # Führt vim in den Insert Mode, nach der Cursorposition
|
||||
v # Führt vim in den Visual Mode
|
||||
: # Führt vim in den Ex Mode
|
||||
<esc> # Führt zurück in den Command Mode, egal in welchem Mode
|
||||
# man sich gerade befindet.
|
||||
i # Führt vim in den Insert Mode, vor der Cursorposition
|
||||
a # Führt vim in den Insert Mode, nach der Cursorposition
|
||||
v # Führt vim in den Visual Mode
|
||||
: # Führt vim in den Ex Mode
|
||||
<esc> # Führt zurück in den Command Mode, egal in welchem Mode
|
||||
# man sich gerade befindet.
|
||||
|
||||
# Kopieren und einfügen von Text
|
||||
# Kopieren und einfügen von Text
|
||||
|
||||
y # Kopiere alles, was im Moment ausgewählt ist
|
||||
yy # Kopiert die aktuelle Zeile
|
||||
d # Löscht alles, was im Moment ausgewählt ist
|
||||
dd # Löscht die aktuelle Zeile
|
||||
p # Fügt den kopierten Text nach dem Cursor ein
|
||||
P # Fügt den kopierten Text vor dem Cursor ein
|
||||
x # Löscht das Zeichen unter dem Cursor
|
||||
y # Kopiere alles, was im Moment ausgewählt ist
|
||||
yy # Kopiert die aktuelle Zeile
|
||||
d # Löscht alles, was im Moment ausgewählt ist
|
||||
dd # Löscht die aktuelle Zeile
|
||||
p # Fügt den kopierten Text nach dem Cursor ein
|
||||
P # Fügt den kopierten Text vor dem Cursor ein
|
||||
x # Löscht das Zeichen unter dem Cursor
|
||||
```
|
||||
|
||||
## Die 'Grammatik' von Vim
|
||||
@ -140,68 +137,67 @@ Vim kann als Satz von Kommandos angesehen werden, welche im Format
|
||||
Einige wichtige Beispiele von 'Verb', 'Modifier' und 'Nouns':
|
||||
|
||||
```
|
||||
# 'Verb'
|
||||
# 'Verb'
|
||||
|
||||
d # löschen
|
||||
c # ändern
|
||||
y # kopieren
|
||||
v # visuelles auswählen
|
||||
d # löschen
|
||||
c # ändern
|
||||
y # kopieren
|
||||
v # visuelles auswählen
|
||||
|
||||
# 'Modifiers'
|
||||
# 'Modifiers'
|
||||
|
||||
i # innerhalb
|
||||
a # außerhalb
|
||||
NUM # Nummer (NUM kann irgendeine Zahl sein)
|
||||
f # Sucht nach etwas und landet darauf
|
||||
t # Sucht nach etwas und stoppt davor
|
||||
/ # Suche eine Zeichenfolge ab dem Cursor
|
||||
? # Suche eine Zeichenfolge vor dem Cursor
|
||||
i # innerhalb
|
||||
a # außerhalb
|
||||
NUM # Nummer (NUM kann irgendeine Zahl sein)
|
||||
f # Sucht nach etwas und landet darauf
|
||||
t # Sucht nach etwas und stoppt davor
|
||||
/ # Suche eine Zeichenfolge ab dem Cursor
|
||||
? # Suche eine Zeichenfolge vor dem Cursor
|
||||
|
||||
# 'Nouns'
|
||||
# 'Nouns'
|
||||
|
||||
w # Wort
|
||||
s # Satz
|
||||
p # Abschnitt
|
||||
b # Block
|
||||
w # Wort
|
||||
s # Satz
|
||||
p # Abschnitt
|
||||
b # Block
|
||||
|
||||
# Beispielsätze resp. Kommandos
|
||||
# Beispielsätze resp. Kommandos
|
||||
|
||||
d2w # lösche zwei Wörter
|
||||
cis # Ändere innerhalb des Satzes.
|
||||
yip # Kopiere innerhalb des Abschnitts (kopiere den Abschnitt,
|
||||
# in welchem du bist)
|
||||
ct< # Ändere bis zur spitzen Klammer
|
||||
# Ändere den Text von deiner aktuellen Cursorposition bis
|
||||
# zur nächsten spitzen Klammer
|
||||
d$ # Lösche bis zum Ende der Zeile
|
||||
d2w # lösche zwei Wörter
|
||||
cis # Ändere innerhalb des Satzes.
|
||||
yip # Kopiere innerhalb des Abschnitts (kopiere den Abschnitt,
|
||||
# in welchem du bist)
|
||||
ct< # Ändere bis zur spitzen Klammer
|
||||
# Ändere den Text von deiner aktuellen Cursorposition bis
|
||||
# zur nächsten spitzen Klammer
|
||||
d$ # Lösche bis zum Ende der Zeile
|
||||
```
|
||||
|
||||
## Einige Shortcuts und Tricks
|
||||
|
||||
```
|
||||
> # Rücke die Auswahl um einen Block ein
|
||||
< # Lösche eine Einrückung der Auswahl
|
||||
:earlier 15m # Stellt das Dokument so wieder her, wie es vor 15
|
||||
# Minuten war
|
||||
:later 15m # den oberen Befehl rückgängig machen
|
||||
ddp # Vertauschen zweier aufeinanderfolgenden Zeilen
|
||||
# Zuerst dd, dann p
|
||||
. # Wiederhole die vorherige Aktion
|
||||
:w !sudo tee % # Speichere die Datei als Root
|
||||
:set syntax=c # Stelle das Syntax-Highlighting für 'C' ein
|
||||
:sort # Alle Zeilen sortieren
|
||||
:sort! # Alle Zeilen rückwärts sortieren
|
||||
:sort u # Alle Zeilen sortieren und Duplikate entfernen
|
||||
~ # Umschalten der Groß-/Kleinschreibung des ausgewählten Textes
|
||||
u # Ausgewählten Text zu Kleinschreibung ändern
|
||||
U # Ausgewählten Text zu Großschreibung ändern
|
||||
|
||||
# Text-Folding (Textfaltung)
|
||||
zf # Erstelle eine Faltung des ausgewählten Textes
|
||||
zo # Öffne die aktuelle Faltung
|
||||
zc # Schließe die aktuelle Faltung
|
||||
zR # Öffne alle Faltungen
|
||||
zM # Schließe alle Faltungen
|
||||
> # Rücke die Auswahl um einen Block ein
|
||||
< # Lösche eine Einrückung der Auswahl
|
||||
:earlier 15m # Stellt das Dokument so wieder her, wie es vor 15 Minuten war
|
||||
:later 15m # den oberen Befehl rückgängig machen
|
||||
ddp # Vertauschen zweier aufeinanderfolgenden Zeilen
|
||||
# Zuerst dd, dann p
|
||||
. # Wiederhole die vorherige Aktion
|
||||
:w !sudo tee % # Speichere die Datei als Root
|
||||
:set syntax=c # Stelle das Syntax-Highlighting für 'C' ein
|
||||
:sort # Alle Zeilen sortieren
|
||||
:sort! # Alle Zeilen rückwärts sortieren
|
||||
:sort u # Alle Zeilen sortieren und Duplikate entfernen
|
||||
~ # Umschalten der Groß-/Kleinschreibung des ausgewählten Textes
|
||||
u # Ausgewählten Text zu Kleinschreibung ändern
|
||||
U # Ausgewählten Text zu Großschreibung ändern
|
||||
|
||||
# Text-Folding (Textfaltung)
|
||||
zf # Erstelle eine Faltung des ausgewählten Textes
|
||||
zo # Öffne die aktuelle Faltung
|
||||
zc # Schließe die aktuelle Faltung
|
||||
zR # Öffne alle Faltungen
|
||||
zM # Schließe alle Faltungen
|
||||
```
|
||||
|
||||
## Makros
|
||||
@ -212,9 +208,9 @@ Kommandos, welche du braucht, aufgenommen bis die Aufnahme gestoppt wird.
|
||||
Wenn du ein Makro ausführst, werden exakt die gleichen Schritte gemacht.
|
||||
|
||||
```
|
||||
qa # Starte das Aufnehmen des Makros 'a'
|
||||
q # Beende das Aufnehmen
|
||||
@a # Führe das Makro 'a' aus
|
||||
qa # Starte das Aufnehmen des Makros 'a'
|
||||
q # Beende das Aufnehmen
|
||||
@a # Führe das Makro 'a' aus
|
||||
```
|
||||
|
||||
### Konfigurieren mit ~/.vimrc
|
||||
|
@ -11,8 +11,8 @@ lang: es-es
|
||||
|
||||
AWK es una herramienta estándar en cada sistema UNIX compatible con POSIX.
|
||||
Es como un Perl restringido, perfecto para tareas de procesamiento de texto y
|
||||
otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin
|
||||
puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo
|
||||
otras necesidades de scripting. Tiene una sintaxis similar a C, pero sin
|
||||
puntos y comas, manejo manual de memoria y tipado estático. Puedes llamarlo
|
||||
desde un script de shell o usarlo como un lenguaje stand-alone para scripting.
|
||||
|
||||
¿Por qué elegir AWK sobre Perl? Principalmente, porque AWK es parte de UNIX.
|
||||
@ -74,8 +74,8 @@ BEGIN {
|
||||
|
||||
# Bloques formados por múltiples líneas usan llaves
|
||||
while (a < 10) {
|
||||
print "La concatenación de strings se hace " " con series "
|
||||
print " de" " strings separados por espacios"
|
||||
print "La concatenación de strings se hace " " con series "
|
||||
print " de" " strings separados por espacios"
|
||||
print a
|
||||
|
||||
a++
|
||||
@ -153,13 +153,13 @@ function arithmetic_functions(a, b, c, localvar) {
|
||||
# Todo es global. No es problema en scripts pequeños, pero sí para
|
||||
# scripts más grandes.
|
||||
|
||||
# Hay un work-around (mmm... hack). Los argumentos de las funciones son
|
||||
# Hay un work-around (mmm... hack). Los argumentos de las funciones son
|
||||
# locales para la función, y AWK permite definir más argumentos de función
|
||||
# de los que necesita, por lo que define las variables locales en la
|
||||
# de los que necesita, por lo que define las variables locales en la
|
||||
# declaración como en la función de arriba. Como convención, agrega
|
||||
# espacios en blanco para distinguir los parámetros de la función de las
|
||||
# variables locales. En este ejemplo, a, b y c son parámetros y localvar es una
|
||||
# variable local.
|
||||
# espacios en blanco para distinguir los parámetros de la función de las
|
||||
# variables locales. En este ejemplo, a, b y c son parámetros y localvar es
|
||||
# una variable local.
|
||||
|
||||
# Ahora, a demostrar las funciones aritméticas
|
||||
|
||||
@ -222,10 +222,10 @@ function io_functions( localvar) {
|
||||
# También hay printf
|
||||
printf("%s %d %d %d\n", "Testing", 1, 2, 3)
|
||||
|
||||
# AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un
|
||||
# handle de archivo cuando use algo que necesite uno. El string que usaste
|
||||
# para esto puede ser tratada como un handle de archivo para propósitos de I/O.
|
||||
# Esto lo hace similar al scripting de shell:
|
||||
# AWK no tiene handles de archivos en sí mismo. Automáticamente abrirá un
|
||||
# handle de archivo cuando use algo que necesite uno. El string que usaste
|
||||
# para esto puede ser tratada como un handle de archivo para propósitos
|
||||
# de I/O. Esto lo hace similar al scripting de shell:
|
||||
|
||||
print "foobar" >"/tmp/foobar.txt"
|
||||
|
||||
@ -247,17 +247,17 @@ function io_functions( localvar) {
|
||||
close("/tmp/foobar.txt")
|
||||
}
|
||||
|
||||
# Como dije al inicio, los programas en AWK son una colección de patrones y
|
||||
# Como dije al inicio, los programas en AWK son una colección de patrones y
|
||||
# acciones. Ya conociste el patrón BEGIN. otros patrones sólo se usan si estás
|
||||
# procesando líneas desde archivos o stdin.
|
||||
|
||||
# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a
|
||||
# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for
|
||||
# Cuando pasas argumentos a AWK, son tratados como nombres de archivos a
|
||||
# procesar. Los va a procesar todos, en orden. Imagínalos como un ciclo for
|
||||
# implícito, iterando sobre las líneas de estos archivos. Estos patrones y
|
||||
# acciones son como instrucciones switch dentro del ciclo.
|
||||
|
||||
/^fo+bar$/ {
|
||||
|
||||
|
||||
# Esta acción se ejecutará por cada línea que haga match con la expresión
|
||||
# regular /^fo+bar$/, y será saltada por cualquier línea que no haga match.
|
||||
# Vamos a sólo mostrar la línea:
|
||||
@ -268,7 +268,7 @@ function io_functions( localvar) {
|
||||
# $0 es el nombre de la línea actual que se está procesando.
|
||||
# Se crea automáticamente para ti.
|
||||
|
||||
# Probablemente puedas adivinar que hay otras variables $. Cada línea es
|
||||
# Probablemente puedas adivinar que hay otras variables $. Cada línea es
|
||||
# separada implícitamente antes de que se llame cada acción, justo como lo
|
||||
# hace shell. Y, como shell, cada campo puede ser accesado con $.
|
||||
|
||||
@ -301,7 +301,7 @@ a > 0 {
|
||||
# Y ya te das una idea. Procesar archivos de texto, leyendo una línea a la vez,
|
||||
# y haciendo algo con ella, particularmente separando en un deliminator, es tan
|
||||
# común en UNIX que AWK es un lenguaje de scripting que hace todo eso por ti
|
||||
# sin que tengas que pedirlo. Basta con escribir los patrones y acciones
|
||||
# sin que tengas que pedirlo. Basta con escribir los patrones y acciones
|
||||
# basados en lo que esperas de la entrada y lo quieras quieras hacer con ella.
|
||||
|
||||
# Aquí está un ejemplo de un script simple, para lo que AWK es perfecto.
|
||||
@ -343,7 +343,7 @@ $1 == name {
|
||||
nlines++
|
||||
}
|
||||
|
||||
# Otro patrón especial es END. Va a ejecutarse después de procesar todos los
|
||||
# Otro patrón especial es END. Va a ejecutarse después de procesar todos los
|
||||
# archivos de texto. A diferencia de BEGIN, sólo se ejecuta si le das dado una
|
||||
# entrada a procesar. Se ejecutará después de que todos los archivos hayan sido
|
||||
# leídos y procesados según las reglas y acciones que programaste. El propósito
|
||||
@ -356,8 +356,10 @@ END {
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Más información:
|
||||
|
||||
* [Tutorial de AWK](http://www.grymoire.com/Unix/Awk.html)
|
||||
* [Página man de AWK](https://linux.die.net/man/1/awk)
|
||||
* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html): GNU Awk se encuentra en la mayoría de los sistemas Linux.
|
||||
* [La guía del usuario de GNU Awk](https://www.gnu.org/software/gawk/manual/gawk.html):
|
||||
GNU Awk se encuentra en la mayoría de los sistemas Linux.
|
||||
|
@ -24,14 +24,12 @@ ce qui concerne le traitement de texte simple. Notamment le traitement de ceux
|
||||
qui nécessitent de lire des fichiers ligne par ligne ; chaque ligne comportant
|
||||
des champs séparés par des délimiteur.
|
||||
|
||||
|
||||
```awk
|
||||
#!/usr/bin/awk -f
|
||||
|
||||
# Les commentaires commencent par un #
|
||||
|
||||
|
||||
# les programmes AWK consistent en une collection de règles et d'actions
|
||||
# Les programmes AWK consistent en une collection de règles et d'actions.
|
||||
règle1 { action; }
|
||||
règle2 { action; }
|
||||
|
||||
@ -46,14 +44,14 @@ règle2 { action; }
|
||||
# texte. Si vous ne disposez pas de fichiers texte, considérez BEGIN comme le
|
||||
# point d’entrée principal du script.
|
||||
# À l'opposé de BEGIN, il existe la règle END. Cette règle est présente après
|
||||
#chaque fin de fichier (EOF : End Of File).
|
||||
# chaque fin de fichier (EOF : End Of File).
|
||||
|
||||
BEGIN {
|
||||
|
||||
# Les variables sont globales. Pas besoin de les déclarer.
|
||||
count = 0;
|
||||
|
||||
# les opérateurs sont identiques au langage C et aux langages similaires
|
||||
# Les opérateurs sont identiques au langage C et aux langages similaires
|
||||
# (tels que C#, C++, etc.)
|
||||
a = count + 1; # addition
|
||||
b = count - 1; # soustraction
|
||||
@ -73,7 +71,8 @@ BEGIN {
|
||||
a++;
|
||||
b--;
|
||||
|
||||
# En tant qu'opérateur préfixé, c'est la valeur incrémentée qui est retournée
|
||||
# En tant qu'opérateur préfixé, c'est la valeur incrémentée qui
|
||||
# est retournée
|
||||
++a;
|
||||
--b;
|
||||
|
||||
@ -121,7 +120,6 @@ BEGIN {
|
||||
arr[1] = "bar";
|
||||
|
||||
# Vous pouvez aussi initialiser un tableau avec la fonction split()
|
||||
|
||||
n = split("foo:bar:baz", arr, ":");
|
||||
|
||||
# Il y a aussi les tableaux associatifs
|
||||
@ -130,7 +128,6 @@ BEGIN {
|
||||
|
||||
# et les tableaux multi-dimensions, avec certaines limitations que l'on ne
|
||||
# mentionnera pas ici
|
||||
|
||||
multidim[0,0] = "foo";
|
||||
multidim[0,1] = "bar";
|
||||
multidim[1,0] = "baz";
|
||||
@ -149,18 +146,16 @@ BEGIN {
|
||||
for (argnum in ARGV)
|
||||
print ARGV[argnum];
|
||||
|
||||
# Vous pouvez supprimer des éléments d'un tableau
|
||||
# Vous pouvez supprimer des éléments d'un tableau.
|
||||
# C'est utile pour empêcher AWK de supposer que certains arguments soient
|
||||
# des fichiers à traiter.
|
||||
|
||||
delete ARGV[1];
|
||||
|
||||
# Le nombre d'arguments de la ligne de commande est assigné à la variable ARGC
|
||||
# Le nombre d'arguments de la ligne de commande est assigné à
|
||||
# la variable ARGC
|
||||
print ARGC;
|
||||
|
||||
# AWK inclue trois catégories de fonction.
|
||||
# On les examinera plus tard
|
||||
|
||||
# AWK inclue trois catégories de fonction. On les examinera plus tard.
|
||||
return_value = arithmetic_functions(a, b, c);
|
||||
string_functions();
|
||||
io_functions();
|
||||
@ -175,13 +170,13 @@ function arithmetic_functions(a, b, c, d) {
|
||||
|
||||
# Il y a cependant une solution de contournement (enfin ... une bidouille).
|
||||
# Les arguments d'une fonction sont locaux à cette fonction.
|
||||
# Et AWK vous permet de définir plus d'arguments à la fonction que nécessaire.
|
||||
# Il suffit donc de mettre une variable locale dans la déclaration de fonction,
|
||||
# comme ci-dessus. La convention veut que vous mettiez quelques espaces
|
||||
# supplémentaires pour faire la distinction entre les paramètres réels et
|
||||
# les variables locales.
|
||||
# Dans cet exemple, a, b et c sont des paramètres réels,
|
||||
# alors que d est simplement une variable locale.
|
||||
# Et AWK vous permet de définir plus d'arguments à la fonction que
|
||||
# nécessaire. Il suffit donc de mettre une variable locale dans la
|
||||
# déclaration de fonction, comme ci-dessus. La convention veut que vous
|
||||
# mettiez quelques espaces supplémentaires pour faire la distinction entre
|
||||
# les paramètres réels et les variables locales.
|
||||
# Dans cet exemple, a, b et c sont des paramètres réels, alors que d est
|
||||
# simplement une variable locale.
|
||||
|
||||
# Maintenant, les fonctions arithmétiques
|
||||
|
||||
@ -217,20 +212,21 @@ function string_functions( localvar, arr) {
|
||||
# AWK a plusieurs fonctions pour le traitement des chaînes de caractères,
|
||||
# dont beaucoup reposent sur des expressions régulières.
|
||||
|
||||
# Chercher et remplacer, la première occurrence (sub) ou toutes les
|
||||
# occurrences (gsub)
|
||||
# Chercher et remplacer, la première occurrence (sub), ou toutes les
|
||||
# occurrences (gsub).
|
||||
# Les deux renvoient le nombre de correspondances remplacées
|
||||
|
||||
localvar = "fooooobar";
|
||||
sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar"
|
||||
gsub("e", ".", localvar); # localvar => "m..t m. at th. bar"
|
||||
|
||||
# Rechercher une chaîne de caractères qui correspond à une expression régulière
|
||||
# index() fait la même chose, mais n'autorise pas les expressions régulières
|
||||
# Rechercher une chaîne de caractères qui correspond à une expression
|
||||
# régulière index() fait la même chose, mais n'autorise pas les expressions
|
||||
# régulières.
|
||||
match(localvar, "t"); # => 4, puisque 't' est le quatrième caractère
|
||||
|
||||
# Séparer par un délimiteur
|
||||
n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
|
||||
n = split("foo-bar-baz", arr, "-");
|
||||
# résultat : a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3
|
||||
|
||||
# Autre astuces utiles
|
||||
sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3"
|
||||
@ -251,23 +247,20 @@ function io_functions( localvar) {
|
||||
|
||||
# AWK n'a pas de descripteur de fichier en soi. Il ouvrira automatiquement
|
||||
# un descripteur de fichier lorsque vous utilisez quelque chose qui en a
|
||||
# besoin.
|
||||
# La chaîne de caractères que vous avez utilisée pour cela peut être traitée
|
||||
# comme un descripteur de fichier à des fins d'entrée / sortie.
|
||||
|
||||
# besoin. La chaîne de caractères que vous avez utilisée pour cela peut être
|
||||
# traitée comme un descripteur de fichier à des fins d'entrée / sortie.
|
||||
outfile = "/tmp/foobar.txt";
|
||||
|
||||
print "foobar" > outfile;
|
||||
|
||||
# Maintenant, la chaîne de caractères "outfile" est un descripteur de fichier.
|
||||
# Vous pouvez le fermer
|
||||
# Maintenant, la chaîne de caractères "outfile" est un descripteur de
|
||||
# fichier. Vous pouvez le fermer.
|
||||
close(outfile);
|
||||
|
||||
# Voici comment exécuter quelque chose dans le shell
|
||||
system("echo foobar"); # => affiche foobar
|
||||
|
||||
# Lire quelque chose depuis l'entrée standard et la stocker dans une variable
|
||||
# locale
|
||||
# Lire quelque chose depuis l'entrée standard et la stocker dans une
|
||||
# variable locale
|
||||
getline localvar;
|
||||
|
||||
# Lire quelque chose à partir d'un pipe (encore une fois, utilisez une
|
||||
@ -294,23 +287,24 @@ function io_functions( localvar) {
|
||||
|
||||
# Cette action sera exécutée pour chaque ligne qui correspond à l'expression
|
||||
# régulière, /^fo+bar$/, et sera ignorée pour toute ligne qui n'y correspond
|
||||
# pas. Imprimons simplement la ligne:
|
||||
# pas. Imprimons simplement la ligne :
|
||||
|
||||
print;
|
||||
|
||||
# Pas d'argument ! C'est parce que print a un défaut : $0.
|
||||
# $0 est le nom de la ligne en cours de traitement. Il est créé automatiquement.
|
||||
# $0 est le nom de la ligne en cours de traitement. Il est créé
|
||||
# automatiquement.
|
||||
|
||||
# Vous devinez probablement qu'il existe d'autres variables $.
|
||||
# Chaque ligne est divisée implicitement avant que chaque action soit exécutée,
|
||||
# comme le fait le shell. Et, comme le shell, chaque champ est accessible
|
||||
# avec un signe dollar
|
||||
# Chaque ligne est divisée implicitement avant que chaque action soit
|
||||
# exécutée, comme le fait le shell. Et, comme le shell, chaque champ est
|
||||
# accessible avec un signe dollar.
|
||||
|
||||
# Ceci affichera les deuxième et quatrième champs de la ligne.
|
||||
# Ceci affichera les deuxième et quatrième champs de la ligne.
|
||||
print $2, $4;
|
||||
|
||||
# AWK défini automatiquement beaucoup d'autres variables qui peuvent vous
|
||||
# aider à inspecter et traiter chaque ligne. La plus importante est NF
|
||||
# aider à inspecter et traiter chaque ligne. La plus importante est NF.
|
||||
|
||||
# Affiche le nombre de champs de la ligne
|
||||
print NF;
|
||||
@ -320,7 +314,6 @@ function io_functions( localvar) {
|
||||
}
|
||||
|
||||
# Chaque règle est en réalité un test conditionnel.
|
||||
|
||||
a > 0 {
|
||||
# Ceci s’exécutera une fois pour chaque ligne, tant que le test est positif
|
||||
}
|
||||
@ -328,19 +321,16 @@ a > 0 {
|
||||
# Les expressions régulières sont également des tests conditionnels.
|
||||
# Si le test de l'expression régulières n'est pas vrais alors le bloc
|
||||
# n'est pas exécuté.
|
||||
|
||||
$0 /^fobar/ {
|
||||
print "la ligne commence par foobar"
|
||||
}
|
||||
|
||||
# Dans le cas où vous voulez tester votre chaîne de caractères sur la ligne
|
||||
# en cours de traitement $0 est optionnelle.
|
||||
|
||||
/^[a-zA-Z0-9]$/ {
|
||||
print "La ligne courante ne contient que des caractères alphanumériques.";
|
||||
}
|
||||
|
||||
|
||||
# AWK peut parcourir un fichier texte ligne par ligne et exécuter des actions en
|
||||
# fonction de règles établies. Cela est si courant sous UNIX qu'AWK est un
|
||||
# langage de script.
|
||||
@ -349,7 +339,7 @@ $0 /^fobar/ {
|
||||
# parfait. Le script lit un nom à partir de l'entrée standard, puis affiche
|
||||
# l'âge moyen de toutes les personnes portant ce prénom.
|
||||
# Supposons que vous fournissiez comme argument le nom d'un fichier comportant
|
||||
# ces données:
|
||||
# ces données :
|
||||
#
|
||||
# Bob Jones 32
|
||||
# Jane Doe 22
|
||||
@ -364,22 +354,24 @@ BEGIN {
|
||||
# Premièrement, on demande à l'utilisateur le prénom voulu
|
||||
print "Pour quel prénom voudriez vous savoir l'age moyen ?";
|
||||
|
||||
# On récupère la ligne à partir de l'entrée standard, pas de la ligne de commande
|
||||
# On récupère la ligne à partir de l'entrée standard, pas de la ligne
|
||||
# de commande :
|
||||
getline name < "/dev/stdin";
|
||||
}
|
||||
|
||||
# Maintenant, pour chaque ligne dont le premier champ est le prénom donné
|
||||
$1 == name {
|
||||
|
||||
# Ici, nous avons accès à un certain nombre de variables utiles déjà préchargées :
|
||||
# Ici, nous avons accès à un certain nombre de variables utiles déjà
|
||||
# préchargées :
|
||||
# $0 est la ligne entière
|
||||
# $3 est le troisième champ. Ici il correspond à l'age qui nous intéresse
|
||||
# NF est le nombre de champs et vaut 3
|
||||
# NR est le nombre d'enregistrements (lignes) vus jusqu'à présent
|
||||
# FILENAME est le nom du fichier en cours de traitement
|
||||
# FS est séparateur de champs, ici c'est " " (un espace)
|
||||
# ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de man.
|
||||
# Pour cela exécutez "man awk" dans votre terminal
|
||||
# ...etc. Et beaucoup d'autre que vous pouvez connaître dans le manuel de
|
||||
# man. Pour cela exécutez "man awk" dans votre terminal.
|
||||
|
||||
# Garder une trace du total accumulé et du nombre de lignes correspondant.
|
||||
sum += $3;
|
||||
@ -390,9 +382,9 @@ $1 == name {
|
||||
# les fichiers texte. Contrairement à BEGIN, il ne fonctionne que si vous lui
|
||||
# donnez une entrée à traiter. Il sera exécuté une fois que tous les fichiers
|
||||
# auront été lus et traités conformément aux règles et aux actions que vous
|
||||
# avez fournies. Le but est généralement de produire un rapport final
|
||||
# ou de faire quelque chose avec l'ensemble des données que vous avez
|
||||
# accumulées au cours du script.
|
||||
# avez fournies. Le but est généralement de produire un rapport final, ou de
|
||||
# faire quelque chose avec l'ensemble des données que vous avez accumulées
|
||||
# au cours du script.
|
||||
|
||||
|
||||
END {
|
||||
@ -401,9 +393,11 @@ END {
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Pour plus d'informations :
|
||||
|
||||
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
|
||||
* [Awk man page](https://linux.die.net/man/1/awk)
|
||||
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk est dans la majorité des systèmes Linux.
|
||||
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html)
|
||||
GNU Awk est dans la majorité des systèmes Linux.
|
||||
* [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html)
|
||||
|
@ -13,8 +13,7 @@ hy to call native python code or python to call native hy code as well
|
||||
This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11.
|
||||
|
||||
```clojure
|
||||
;; this gives an gentle introduction to hy for a quick trial head to
|
||||
;; http://try-hy.appspot.com
|
||||
;; this gives an gentle introduction to hy
|
||||
;;
|
||||
; Semicolon comments, like other LISPS
|
||||
|
||||
|
@ -370,8 +370,10 @@ END {
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Leituras adicionais (em inglês):
|
||||
|
||||
* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html)
|
||||
* [Awk man page](https://linux.die.net/man/1/awk)
|
||||
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU AWK é encontrado na maioria dos sistemas GNU/Linux.
|
||||
* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html)
|
||||
GNU AWK é encontrado na maioria dos sistemas GNU/Linux.
|
||||
|
480
pt-br/processing-pt.html.markdown
Normal file
480
pt-br/processing-pt.html.markdown
Normal file
@ -0,0 +1,480 @@
|
||||
---
|
||||
language: processing
|
||||
filename: learnprocessing.pde
|
||||
contributors:
|
||||
- ["Phone Thant Ko", "http://github.com/phonethantko"]
|
||||
- ["Divay Prakash", "https://github.com/divayprakash"]
|
||||
translators:
|
||||
- ["Kemel Zaidan", "https://github.com/kemelzaidan"]
|
||||
lang: pt-br
|
||||
---
|
||||
|
||||
## Introdução
|
||||
|
||||
Processing é uma linguagem de programação para criação de artes digitais e
|
||||
conteúdo multimídia, permitindo que não programadores aprendam os fundamentos
|
||||
da programação computacional em um contexto visual.
|
||||
|
||||
Embora a linguagem seja baseada na linguagem Java, sua sintaxe foi amplamente
|
||||
influenciado por ambas as sintaxes Java e Javascript.
|
||||
[Veja mais aqui](https://processing.org/reference/)
|
||||
|
||||
A linguagem é tipada estaticamente e também vem com o seu Ambiente de Desenvolvimento
|
||||
Integrado (do inglês Integrated Development Environment - IDE) oficial para
|
||||
compilar e executar os scripts.
|
||||
|
||||
```
|
||||
/* ---------
|
||||
Comentários
|
||||
---------
|
||||
*/
|
||||
|
||||
// Comentário de linha única começa com //
|
||||
|
||||
/*
|
||||
Como o Processing é baseado em Java,
|
||||
a sintaxe para seus comentários é a mesma do Java (como você deve ter notado
|
||||
acima)!
|
||||
Comentários de várias linhas são agrupados como visto aqui.
|
||||
*/
|
||||
|
||||
/* ---------------------------------------
|
||||
Escrevendo e executando programas em Processing
|
||||
---------------------------------------
|
||||
*/
|
||||
|
||||
// No Processing, o ponto de entrada do programa é uma função chamada setup()
|
||||
// com um tipo de retorno void.
|
||||
// Observação! A sintaxe é muito semelhante à do C++.
|
||||
void setup() {
|
||||
// Isso imprime a saída clássica "Hello World!" no console quando executado.
|
||||
println("Olá Mundo!"); // Mais uma linguagem com esse maldito ponto e vírgula, não é?
|
||||
}
|
||||
|
||||
// Normalmente, colocamos todos os códigos estáticos dentro do método setup()
|
||||
// como o próprio nome sugere, uma vez que é executado apenas uma vez.
|
||||
// Pode variar da definição das cores de fundo, ou o tamanho da tela.
|
||||
background(color); //define a cor do fundo
|
||||
size(largura,altura,[renderizador]); // define o tamanho da tela com parâmetro
|
||||
// opcional para definir o renderizador
|
||||
// Você verá mais sobre isso ao longo deste documento.
|
||||
|
||||
// Se você deseja executar os códigos indefinidamente, eles devem ser colocados
|
||||
// dentro do método draw()
|
||||
// draw() deve existir caso você queira que o código seja executado
|
||||
// continuamente e, obviamente, só pode haver um método draw().
|
||||
int = 0;
|
||||
void draw(){
|
||||
// Este bloco de código faz um loop para sempre até parar
|
||||
imprima(i);
|
||||
i++; // Operador de incremento!
|
||||
}
|
||||
|
||||
// Agora que sabemos como escrever o script de trabalho e como executá-lo,
|
||||
// continuaremos a explorar quais tipos de dados e coleções são suportados no
|
||||
// Processing.
|
||||
|
||||
/* ------------------------
|
||||
Tipos de dados e coleções
|
||||
------------------------
|
||||
*/
|
||||
|
||||
// De acordo com as Referências do Processing, ele suporta 8 tipos primitivos
|
||||
// de dados da seguinte forma.
|
||||
|
||||
boolean valorBoleano = true; // Boleano
|
||||
byte valorByteDeA = 23; // Byte
|
||||
char valorCharDeA = 'A'; // Caractere
|
||||
color valorDeCorBrancoM = color(255, 255, 255); // Cor (especificada usando
|
||||
// método color())
|
||||
color valorDeCorBrancoH = #FFFFFF; // Cor (especificada usando valor de hash)
|
||||
int valor = 5; // Inteiro (Número sem decimais)
|
||||
long valorLongo = 2147483648L; // "L" é adicionado ao número para marcá-lo como um longo
|
||||
float valorFloat = 1,12345; // Float (números de ponto flutuante de 32 bits)
|
||||
double valorDouble = 1,12345D; // Double (números de ponto flutuante de 64 bits)
|
||||
|
||||
// NOTA!
|
||||
// Embora os tipos de dados "long" e "double" funcionem na linguagem,
|
||||
// funções do Processing não usam esses tipos de dados, portanto
|
||||
// eles precisam ser convertidos em tipos de dados "int" e "float",
|
||||
// respectivamente, usando a sintaxe (int) e (float) antes de passar para uma
|
||||
// função.
|
||||
|
||||
// Existem vários tipos de dados compostos que estão disponíveis por padrão para
|
||||
// uso no Processing.
|
||||
// Primeiramente, farei um resumo dos mais usados para economizar tempo.
|
||||
|
||||
// String
|
||||
// Enquanto o tipo de dados char usa '', o tipo de dados String usa "" - aspas
|
||||
// duplas.
|
||||
string stringExemplo = "Olá, Processing!";
|
||||
// String também pode ser criada a partir de um array de tipos de dados char.
|
||||
// Nós vamos discutir array muito em breve.
|
||||
char fonte = {'H', 'E', 'L', 'L', 'O'};
|
||||
String stringDeFonte = new String(source); // HELLO
|
||||
// Como em Java, strings podem ser concatenadas usando o operador "+".
|
||||
print("Olá " + "Mundo!"); // Olá Mundo!
|
||||
|
||||
// Array
|
||||
// Arrays em Processing podem conter quaisquer tipos de dados, incluindo os
|
||||
// próprios objetos. Como os arrays são semelhantes aos objetos, eles devem
|
||||
// ser criados com a palavra-chave "new".
|
||||
int[] arrayInt = new int[5];
|
||||
int[] arrayIntComValores = {1, 2, 3}; // Você também pode preencher com dados.
|
||||
|
||||
// Lista de Arrays
|
||||
// As funções são semelhantes às do array; arraylists podem conter qualquer
|
||||
// tipo de dados. A única diferença é que as listas de matrizes são
|
||||
// redimensionadas dinamicamente, pois é uma forma de implementação de matriz
|
||||
// redimensionável da interface "List" do Java .
|
||||
ArrayList<Integer> intArrayList = new ArrayList<Integer>();
|
||||
|
||||
// Objeto
|
||||
// Como é baseado em Java, o Processing suporta programação orientada a objetos.
|
||||
// Isso significa que você pode basicamente definir quaisquer tipos de dados de
|
||||
// sua preferência e manipulá-los para suas necessidades.
|
||||
// Claro, uma classe tem que ser definida antes para o objeto que você quer.
|
||||
// Formato --> NomeClasse NameInstancia
|
||||
UmaClasseQualquer meuObjeto // então instancia mais tarde
|
||||
//ou
|
||||
UmaClasseQualquer meuObjetoInstanciado = new UmaClasseQualquer();
|
||||
|
||||
// O Processing surge com mais coleções (ex. - Dicionários e Listas) por
|
||||
// padrão, por uma questão de simplicidade, vou deixá-los fora da discussão aqui.
|
||||
|
||||
/* ------------
|
||||
Matemática
|
||||
------------
|
||||
*/
|
||||
|
||||
// Aritmética
|
||||
1 + 1 // 2
|
||||
2 - 1 // 1
|
||||
2 * 3 // 6
|
||||
3/2 // 1
|
||||
3.0 / 2 // 1.5
|
||||
3.0% 2 // 1.0
|
||||
|
||||
// O Processing também vem com um conjunto de funções que simplificam operações
|
||||
// matemáticas.
|
||||
float f = sq(3); // f = 9.0
|
||||
float p = pow(3, 3); // p = 27.0
|
||||
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
|
||||
|
||||
// Vetores
|
||||
// O Processing fornece uma maneira fácil de implementar vetores em seu ambiente
|
||||
// usando a classe PVector. Ela pode descrever um vetor bi ou tridimensional e
|
||||
// vem com um conjunto de métodos que são úteis para operações com matrizes.
|
||||
// Você pode encontrar mais informações sobre a classe PVector e suas funções
|
||||
// aqui. (https://processing.org/reference/PVector.html)
|
||||
|
||||
// Trigonometria
|
||||
// O Processing também suporta operações trigonométricas fornecendo um
|
||||
// conjunto de funções. sin(), cos(), tan(), asin(), acos(), atan() e também
|
||||
// degrees() e radians() para conversão conveniente.
|
||||
// No entanto, essas funções usam o ângulo em radianos como parâmetro, então é
|
||||
// necessário converter previamente.
|
||||
float um = sin(PI/2); // um = 1.0
|
||||
// Como você deve ter notado, existe um conjunto de constantes para usos
|
||||
// trigonométricos; PI, HALF_PI, QUARTER_PI e assim por diante...
|
||||
|
||||
/* -------------
|
||||
Controle de fluxo
|
||||
-------------
|
||||
*/
|
||||
|
||||
// Declarações Condicionais
|
||||
// Instruções If - A mesma sintaxe das instruções if em Java.
|
||||
if (author.getAppearance().equals("quente")) {
|
||||
print("Narcisismo no máximo!");
|
||||
} else {
|
||||
// Você pode verificar outras condições aqui.
|
||||
print("Algo está realmente errado aqui!");
|
||||
}
|
||||
// Um atalho para instruções if-else também pode ser usado.
|
||||
int = 3;
|
||||
String valor = (i > 5) ? "Grande" : "Pequena"; // "Pequena"
|
||||
|
||||
// A estrutura switch-case pode ser usada para verificar várias condições de
|
||||
// forma concisa. É importante usar a instrução break. Se a instrução `break`
|
||||
// não existe o programa executa todos os casos a seguir após um caso ser
|
||||
// verdadeiro.
|
||||
int valor = 2;
|
||||
switch(valor) {
|
||||
case 0:
|
||||
print("Nada!"); // Isso não é executado.
|
||||
break; // Salta para a próxima instrução
|
||||
case 1:
|
||||
print("Chegando lá..."); // Isso novamente não é executado.
|
||||
break;
|
||||
case 2:
|
||||
print("Bravo!"); // Esta linha é executada.
|
||||
break;
|
||||
default:
|
||||
print("Não encontrado!"); // Esta linha é executada se nosso valor for algum outro valor.
|
||||
break;
|
||||
}
|
||||
|
||||
// Declarações iterativas
|
||||
// Declarações For - Novamente, a mesma sintaxe que em Java
|
||||
for(int i = 0; i < 5; i++){
|
||||
print(i); // imprime de 0 a 4
|
||||
}
|
||||
|
||||
// Declarações While - Novamente, nada de novo se você estiver familiarizado com
|
||||
// a sintaxe Java.
|
||||
int j = 3;
|
||||
while(j > 0) {
|
||||
print(j);
|
||||
j--; // Isso é importante para evitar que o código seja executado indefinidamente.
|
||||
}
|
||||
|
||||
// loop()| noLoop() | redraw() | exit()
|
||||
// Estas são mais funções específicas do Processing para configurar o fluxo do
|
||||
// programa.
|
||||
loop(); // permite que o método draw() seja executado para sempre enquanto
|
||||
noLoop(); // só permite que ele seja executado uma vez.
|
||||
redraw(); // executa o método draw() mais uma vez.
|
||||
exit(); // Isso para o programa. É útil para programas com draw()
|
||||
// rodando continuamente.
|
||||
```
|
||||
|
||||
## Desenho com Processing
|
||||
|
||||
Como você já deve ter entendido o básico da linguagem, vamos agora
|
||||
ver a melhor parte do Processing - DESENHAR.
|
||||
|
||||
```
|
||||
/* ------
|
||||
Formas
|
||||
------
|
||||
*/
|
||||
|
||||
// Formas 2D
|
||||
|
||||
// Ponto
|
||||
point(x, y); // No espaço 2D
|
||||
point(x, y, z); // No espaço 3D
|
||||
// Desenha um ponto no espaço de coordenadas.
|
||||
|
||||
// Linha
|
||||
line(x1, y1, x2, y2); // No espaço 2D
|
||||
line(x1, y1, z1, x2, y2, z2); // No espaço 3D
|
||||
// Desenha uma linha conectando dois pontos definidos por (x1, y1) e (x2, y2).
|
||||
|
||||
// Triângulo
|
||||
triangle(x1, y1, x2, y2, x3, y3);
|
||||
// Desenha um triângulo conectando três pontos definidos por parâmetros de coordenadas.
|
||||
|
||||
// Retângulo
|
||||
rect(a, b, c, d, [r]); // Com parâmetro opcional definindo o raio de todos os cantos
|
||||
rect(a, b, c, d, [te, td, bd, be]); // Com conjunto opcional de parâmetros definindo
|
||||
// raio de cada canto
|
||||
// Desenha um retângulo com {a, b} como coordenada superior esquerda e c e d como largura
|
||||
// e altura respectivamente.
|
||||
|
||||
// Quad
|
||||
quad(x, y, x2, y2, x3, y3, x4, y4);
|
||||
// Desenha um quadrilátero com parâmetros que definem as coordenadas de cada canto
|
||||
// ponto.
|
||||
|
||||
// Elipse
|
||||
ellipse(x, y, largura, altura);
|
||||
// Desenha um eclipse no ponto {x, y} com largura e altura especificadas.
|
||||
|
||||
// Arco
|
||||
arc(x, y, largura, altura, inicio, fim, [modo]);
|
||||
// Enquanto os primeiros quatro parâmetros são autoexplicativos,
|
||||
// início e fim definem os ângulos que o arco começa e termina (em radianos).
|
||||
// O parâmetro opcional [mode] define o preenchimento;
|
||||
// PIE dá o contorno de torta, CHORD dá o contorno reto e OPEN é como
|
||||
// CHORD porém sem contorno
|
||||
|
||||
// Curvas
|
||||
// O Processing fornece duas implementações de curvas; usando curve() e
|
||||
// bezier(). Como pretendo manter isso simples, não vou discutir mais detalhes.
|
||||
// No entanto, se você quiser implementá-lo em seu sketch, aqui estão as
|
||||
// referências: (https://processing.org/reference/curve_.html)
|
||||
// (https://processing.org/reference/bezier_.html)
|
||||
|
||||
// Formas 3D
|
||||
|
||||
// espaço 3D
|
||||
pode ser configurado definindo "P3D" para o parâmetro do renderizador no
|
||||
// método size().
|
||||
size(largura, altura, P3D);
|
||||
// No espaço 3D, você terá que traduzir para a coordenada específica para
|
||||
// renderiza as formas 3D.
|
||||
|
||||
// Caixa
|
||||
box(tamanho); // Cubo com o mesmo comprimento definido pelo tamanho
|
||||
box(w, h, d); // Caixa com largura, altura e profundidade definidas separadamente
|
||||
|
||||
// Esfera
|
||||
sphere(raio); // Seu tamanho é definido usando o parâmetro raio
|
||||
// O mecanismo por trás da renderização das esferas é implementado por
|
||||
// triângulos em mosaico. Dito isso, o nível de detalhe sendo renderizado é
|
||||
// controlado pela função sphereDetail(res)
|
||||
// Mais informações aqui: (https://processing.org/reference/sphereDetail_.html)
|
||||
|
||||
// Formas irregulares
|
||||
// E se você quiser desenhar algo que não foi disponibilizado pelo Processing
|
||||
// funções?
|
||||
// Você pode usar beginShape(), endShape(), vertex(x,y) para definir formas por
|
||||
// especificando cada ponto. Mais informações aqui:
|
||||
// (https://processing.org/reference/beginShape_.html)
|
||||
// Você também pode usar formas personalizadas usando a classe PShape:
|
||||
// (https://processing.org/reference/PShape.html)
|
||||
|
||||
/* ---------------
|
||||
Transformações
|
||||
---------------
|
||||
*/
|
||||
|
||||
// As transformações são particularmente úteis para acompanhar o espaço de
|
||||
// coordenadas e os vértices das formas que você desenhou. Particularmente;
|
||||
// métodos de pilha de matrizes; pushMatrix(), popMatrix() e translate(x,y)
|
||||
pushMatriz(); // Salva o sistema de coordenadas atual na pilha
|
||||
// ... aplique todas as transformações aqui ...
|
||||
popMatriz(); // Restaura o sistema de coordenadas salvo
|
||||
// Usando-os, o sistema de coordenadas pode ser preservado e visualizado sem
|
||||
// causar qualquer conflito.
|
||||
|
||||
// Traduzir
|
||||
translate(x,y); // Traduz para o ponto{x, y} ou seja - configurando a origem para esse ponto
|
||||
translate(x, y, z); // Contraparte 3D da função
|
||||
|
||||
// Rotacionar
|
||||
rotate(ângulo); // Gira a quantidade especificada pelo parâmetro ângulo
|
||||
// Possui 3 contrapartes 3D para realizar a rotação, uma para cada dimensão:
|
||||
// rotateX(ângulo), rotateY(ângulo), rotateZ(ângulo)
|
||||
|
||||
// Escala
|
||||
scale(s); // Dimensiona o sistema de coordenadas expandindo ou contraindo-o.
|
||||
|
||||
/* --------------------
|
||||
Estilo e texturas
|
||||
--------------------
|
||||
*/
|
||||
|
||||
// Cores
|
||||
// Como discuti anteriormente, a cor de fundo pode ser configurada usando a
|
||||
// função background(). Você pode definir a cor de um objeto de antemão e depois
|
||||
// passar para a função como um argumento.
|
||||
color c = cor(255, 255, 255); // BRANCO!
|
||||
// Por padrão, o Processing usa o esquema de cores RGB, mas pode ser configurado
|
||||
// para HSB usando colorMode(). Leia mais aqui:
|
||||
// (https://processing.org/reference/colorMode_.html)
|
||||
background(c); // Até agora, a cor de fundo deve ser branca.
|
||||
// Você pode usar a função fill() para selecionar a cor para preencher as formas.
|
||||
// Tem que ser configurado antes de você começar a desenhar formas para que as
|
||||
// cores fiquem aplicadas.
|
||||
fill(color(0, 0, 0));
|
||||
// Se você quiser apenas colorir os contornos das formas, você pode usar
|
||||
// função stroke().
|
||||
stroke(255, 255, 0, 200); // cor do traço definida para amarelo com transparência
|
||||
// definido para um valor menor.
|
||||
|
||||
// Imagens
|
||||
// O Processing pode renderizar imagens e usá-las de várias maneiras.
|
||||
// Principalmente armazenado como Tipo de dados PImage.
|
||||
filter(sombreador); // O Processing suporta várias funções de filtro para manipulação de imagens.
|
||||
texture(imagem); // PImage pode ser passado em argumentos para mapeamento de textura das formas.
|
||||
```
|
||||
|
||||
Se você quiser levar as coisas adiante, há mais coisas que o Processing tem o poder de fazer. Renderizar modelos, shaders e outros efeitos. Há muito para se cobrir em uma
|
||||
documentação curta, então vou deixá-los aqui. Se você se interessar, por favor verifique as referências.
|
||||
|
||||
```
|
||||
// Antes de prosseguirmos, vou falar um pouco mais sobre como importar bibliotecas
|
||||
// para que você possa estender a funcionalidade do Processing para outros horizontes.
|
||||
|
||||
/* -------
|
||||
Importações
|
||||
-------
|
||||
*/
|
||||
|
||||
// As possibilidades do Processing pode ser estendidas ainda mais quando
|
||||
// importamos bibliotecas e pacotes em nossos esboços.
|
||||
// A instrução de importação pode ser escrita como abaixo na parte superior
|
||||
// do código-fonte.
|
||||
import processing.algumacoisa.*;
|
||||
```
|
||||
|
||||
## VAC?
|
||||
|
||||
Vamos ao código? Vamos sujar as mãos!
|
||||
|
||||
Vamos ver um exemplo do openprocessing para visualizar o quanto o Processing é
|
||||
capaz de fazer com poucas linhas de código.
|
||||
|
||||
Copie o código abaixo em seu IDE do Processing e veja a mágica.
|
||||
|
||||
```
|
||||
// Isenção de responsabilidade: eu não escrevi este programa porque atualmente
|
||||
// estou ocupado com meu estágio e este sketch é adaptado do openprocessing pois
|
||||
// mostra algo legal com um código simples.
|
||||
// Recuperado de: (https://www.openprocessing.org/sketch/559769)
|
||||
|
||||
float theta;
|
||||
float a;
|
||||
float col;
|
||||
float num;
|
||||
|
||||
void setup() {
|
||||
size(600,600);
|
||||
}
|
||||
|
||||
void draw() {
|
||||
background(#F2F2F2);
|
||||
translate(width/2, height/2);
|
||||
theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6);
|
||||
|
||||
float num=6;
|
||||
for (int i=0; i<num; i++) {
|
||||
a =350;
|
||||
rotate(TWO_PI/num);
|
||||
branch(a);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void branch(float len) {
|
||||
col=map(len, 0, 90, 150, 255);
|
||||
fill(col, 0, 74);
|
||||
stroke (col, 0, 74);
|
||||
line(0, 0, 0, -len);
|
||||
ellipse(0, -len, 3, 3);
|
||||
len *= 0.7;
|
||||
|
||||
if (len>30) {
|
||||
pushMatrix();
|
||||
translate(0, -30);
|
||||
rotate(theta);
|
||||
branch(len);
|
||||
popMatrix();
|
||||
|
||||
pushMatrix();
|
||||
translate(0, -30);
|
||||
rotate(-theta);
|
||||
branch(len);
|
||||
popMatrix();
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A linguagem Processing é fácil de aprender e é particularmente útil para criar
|
||||
conteúdo (mesmo em 3D) sem ter que digitar muitos códigos. É tão simples
|
||||
que você pode ler o código e ter uma ideia aproximada do fluxo do programa.
|
||||
|
||||
No entanto, isso não se aplica quando você introduz bibliotecas externas, pacotes
|
||||
e até mesmo suas próprias aulas. (Confie em mim! Projetos em processing podem ficar realmente monstruosos...)
|
||||
|
||||
## Alguns recursos úteis
|
||||
|
||||
- [Site do Processing](http://processing.org)
|
||||
- [Sketches em Processing](http://openprocessing.org)
|
@ -11,7 +11,7 @@ contributors:
|
||||
" ##############
|
||||
"
|
||||
" Vim script (also called VimL) is the subset of Vim's ex-commands which
|
||||
" supplies a number of features one one would expect from a scripting language,
|
||||
" supplies a number of features one would expect from a scripting language,
|
||||
" such as values, variables, functions or loops. Always keep in the back of
|
||||
" your mind that a Vim script file is just a sequence of ex-commands. It is
|
||||
" very common for a script to mix programming-language features and raw
|
||||
|
Loading…
Reference in New Issue
Block a user