-
-
Notifications
You must be signed in to change notification settings - Fork 109
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
52 changed files
with
7,630 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
# The URL of the site. It is used in the atom feed, the sitemap, the Open Graph meta field of each page, and the robots.txt | ||
# No trailing slashes! | ||
url: https://es.code-maven.com | ||
|
||
# site_name is used in the atom feed and in the Open Graph meta field of each page | ||
site_name: Code Maven en Español con errores gramaticales | ||
|
||
# The source of the https://rust.code-maven.com site is in a public git repository | ||
# using the 'main' branch. | ||
# We wanted each page on the site to link directly to the source of that page. | ||
# The following 3 parameters help do this. | ||
# You can disable this feature by keeping `link_to_source` as `false`. | ||
# You can enable this feature by putting the correct repo link and correct branch name | ||
# and setting `link_to_source` to `true` | ||
repo: https://github.com/szabgab/es.code-maven.com | ||
branch: main | ||
link_to_source: false | ||
|
||
# Each page will have a footer as defined by the `footer` field that can contain markdown. | ||
footer: "[Code Maven](https://code-maven.com/) en ingles" | ||
|
||
# Each site has a /tags page generated from the tags in the individual pages. | ||
# The following parameters set the `title` of the page and the content of the `description` meta-tag. | ||
tags: | ||
title: Tags | ||
description: Articles about Foo Bar | ||
|
||
# Each site has a /archive page generated from all the pages, except the main page (the root index.md file). | ||
# The following parameters set the `title` of the page and the content of the `description` meta-tag. | ||
archive: | ||
title: Archivo | ||
description: Archivo de este sitio | ||
|
||
# If you have setup Google Analytics add your code here and uncomment the following field | ||
# google_analytics: G-BLABLA | ||
|
||
|
||
# Fields used by the email sender | ||
# TODO: Explain the whole email sending via `sendgrid` | ||
from: | ||
name: Foo Bar | ||
email: [email protected] | ||
|
||
# On each page show the list of pages that link to the current page. | ||
# Define the title of the section when the related pages are shown | ||
show_related: true | ||
related_pages_title: Otras páginas | ||
|
||
# Each page can have an `author` field in the front-matter containing the nickname of the author. | ||
# Here we list all the authors of the site. | ||
# The name will be displayed on the page | ||
# In addition there can be a folder called `authors` with makrdown files using the nicknames (so in the example it would be authors/foobar.md) | ||
# Those file can contain information about the author that will be displayed at the bottom of each page. | ||
# TODO: where is the image located | ||
authors: | ||
- name: Gabor Szabo | ||
nickname: szabgab | ||
picture: szabgab.png | ||
- name: Jeffrey Thalhammer | ||
nickname: thalhammer | ||
picture: thalhammer.png | ||
|
||
# The following section defines the menu. The "start" will be left-aligned the "end" will be right aligned. | ||
# TODO: Once we implement rtl site this will probably be the other direction too | ||
# TODO: Support also drop-down menus | ||
navbar: | ||
start: | ||
- path: / | ||
title: Casa | ||
- path: /tags/ | ||
title: Tags | ||
end: | ||
- path: /archive | ||
title: Archivo | ||
- path: /about | ||
title: About | ||
|
||
# search: Resultsos de buscada |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
--- | ||
title: "About Perl Maven" | ||
timestamp: 2012-05-02T00:01:33 | ||
published: true | ||
original: about | ||
archive: false | ||
--- | ||
|
||
|
||
Placeholder. Check out the [English version](https://perlmaven.com/). |
159 changes: 159 additions & 0 deletions
159
sites/ru/pages/avtomaticheskiy-perevod-znacheniy-ili-privedenie-tipov-v-perl.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
--- | ||
title: "Автоматический перевод строк в числа или приведение типов в Perl" | ||
timestamp: 2013-07-09T08:00:00 | ||
tags: | ||
- is_number | ||
- looks_like_number | ||
- Scalar::Util | ||
- casting | ||
- type conversion | ||
published: true | ||
original: automatic-value-conversion-or-casting-in-perl | ||
books: | ||
- beginner | ||
author: szabgab | ||
translator: spidamoo | ||
--- | ||
|
||
|
||
Представьте, что, составляя список покупок, пишете на листке | ||
|
||
``` | ||
"2 буханки хлеба" | ||
``` | ||
|
||
и отдаете его своей второй половине, которая тут же выбрасывает ошибку неправильного перевода | ||
типов прямо вам в лицо. Ведь, действительно, "2" здесь - это строка, а не число. | ||
|
||
Это было бы то еще разочарование, не правда ли? | ||
|
||
|
||
## Перевод типов в Perl | ||
|
||
В большинсте языков программирования тип операнда определяет поведение оператора. | ||
То есть <i>прибавление</i> одного числа к другому выполнится как числовое сложение, | ||
а <i>прибавление</i> двух строк - как конкатенация. Это свойство называется перегрузкой операторов. | ||
|
||
Perl по большей части работает наоборот. | ||
|
||
В Perl оператор определяет, как будут использоваться операнды. | ||
|
||
Таким образом, если вы используете числовую операцию (например, сложение), то оба значения | ||
автоматически преобразуются в числа. Если вы используете строковую операцию (например, конкатенацию), | ||
оба значения автоматически преобразуются в строки. | ||
|
||
C-программисты, должно быть, назовут эти преобразования приведением типов, но это выражение не | ||
используется в мире Perl. Возможно, потому, что все происходит само собой. | ||
|
||
Для Perl'а не важно, пишете вы что-то как строку или как число. Он конвертирует их друг в друга | ||
автоматически, основываясь на контексте. | ||
|
||
Преобразование <h1>число => строка</h1> это просто. Мы просто представляем, что вокруг числа | ||
появляются кавычки "". | ||
|
||
Преобразование <h1>строка => число</h1> может немного озадачить. Если строка выглядит для perl'а как | ||
число, то все просто. Числовое значение будет тем же самым, только без кавычек. | ||
|
||
Если же встречается символ, который не дает perl'у полностью превратить строку в число, то он | ||
использует как число столько, сколько сможет, из левой части строки, и проигнорирует остальное. | ||
|
||
Позвольте продемонстрировать вам пару примеров: | ||
|
||
``` | ||
Исходное значение Строка Число | ||
42 "42" 42 | ||
0.3 "0.3" 0.3 | ||
"42" "42" 42 | ||
"0.3" "0.3" 0.3 | ||
"4z" "4z" 4 (*) | ||
"4z3" "4z3" 4 (*) | ||
"0.3y9" "0.3y9" 0.3 (*) | ||
"xyz" "xyz" 0 (*) | ||
"" "" 0 (*) | ||
"23\n" "23\n" 23 | ||
``` | ||
|
||
Во всех случаях, когда перевод строки в число не полон, кроме последнего, perl выдаст предупреждение. | ||
Ну, предполагается, что вы включили `use warnings` в соответствии с рекомендациями. | ||
|
||
## Пример | ||
|
||
Теперь давайте посмотрим в коде то, что вы видели в таблице: | ||
|
||
```perl | ||
use strict; | ||
use warnings; | ||
|
||
my $x = "4T"; | ||
my $y = 3; | ||
|
||
``` | ||
|
||
Конкатенация превращает оба значения в строки: | ||
|
||
```perl | ||
print $x . $y; # 4T3 | ||
``` | ||
|
||
Сложение превращает оба значения в числа: | ||
|
||
```perl | ||
print $x + $y; # 7 | ||
# Argument "4T" isn't numeric in addition (+) at ... | ||
``` | ||
|
||
## Argument isn't numeric | ||
|
||
Это предупреждение, которое вы получите, когда perl попытается конвертировать строку в число, но | ||
перевод не полон. | ||
|
||
Существуют некоторые других распространенных предупреждений и ошибок в Perl. | ||
Например, [Global symbol requires explicit package name](/global-symbol-requires-explicit-package-name) | ||
и [Use of uninitialized value](/use-of-uninitialized-value). | ||
|
||
## Как избавиться от предупреждения? | ||
|
||
Это приятно, что perl предупреждает вас (если попросить), когда перевод типов не полон, но | ||
нет ли функции вроде <b>is_number</b>, которая проверит, является ли данная строка числом? | ||
|
||
Да и нет. | ||
|
||
В Perl нет функции <b>is_number</b>, потому что это стало бы заявлением, будто бы программисты Perl | ||
знают, что является числом, а что нет. К сожалению, остальная часть мира не может прийти к | ||
окончательному соглашению по этому вопросу. Существуют системы, в которых строка ".2" признается | ||
числом, но в других системах она таковым не является. Еще более простой случай - "2.", как | ||
правило, не признается, но есть система, в которой это совершенно допустимое число. | ||
|
||
Есть даже места, где 0xAB считается числом. Шестнадцатеричным. | ||
|
||
Так что функции <b>is_number</b> не существует, но есть менее категоричные функции, такие как | ||
<b>looks_like_number</b>. | ||
|
||
Это именно то, что вы думаете. Функция проверит, будет ли данная строка похожа на число для perl'а. | ||
|
||
Она содержится в модуле [Scalar::Util](http://perldoc.perl.org/Scalar/Util.html) и ее | ||
используют следующим образом: | ||
|
||
```perl | ||
use strict; | ||
use warnings; | ||
|
||
use Scalar::Util qw(looks_like_number); | ||
|
||
print "Сколько буханок хлеба мне купить? "; | ||
my $loaves = <STDIN>; | ||
chomp $loaves; | ||
|
||
if (looks_like_number($loaves)) { | ||
print "Я пошел...\n"; | ||
} else { | ||
print "Извини, я не понял\n"; | ||
} | ||
``` | ||
|
||
|
||
И не забудь молоко! | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
--- | ||
title: "Barewords - "голые" слова в Perl" | ||
timestamp: 2013-07-25T13:00:01 | ||
tags: | ||
- bareword | ||
- strict | ||
published: true | ||
original: barewords-in-perl | ||
books: | ||
- beginner | ||
author: szabgab | ||
translator: spidamoo | ||
--- | ||
|
||
|
||
`use strict` состоит из трех частей. Одна из них ( `use strict "subs"`) запрещает | ||
неправильное использование <b>barewords</b>. | ||
|
||
Что это значит? | ||
|
||
|
||
Без этого ограничения такой код бы сработал и выдал "hello". | ||
|
||
```perl | ||
my $x = hello; | ||
print "$x\n"; # hello | ||
``` | ||
|
||
Это само по себе странно, потому что мы привыкли помещать строки в кавычки, но Perl по умолчанию | ||
позволяет использовать "голые слова" (<b>barewords</b>) - слова без кавычек - в качестве строк. | ||
|
||
Поэтому код из примера выше выдаст "hello". | ||
|
||
Ну, по крайней мере пока кто-нибудь не добавит подпрограмму "hello" в начало вашего скрипта: | ||
|
||
```perl | ||
sub hello { | ||
return "zzz"; | ||
} | ||
|
||
my $x = hello; | ||
print "$x\n"; # zzz | ||
``` | ||
|
||
Да. В этой версии perl видит подпрограмму hello(), вызывает ее и присваивает возвращаемое ей | ||
значение переменной $x. | ||
|
||
Однако, если кто-то переместит эту подпрограмму в конец файла, после присвоения, perl внезапно | ||
перестанет видеть ее во время присвоения, и мы снова получаем "hello" в $x. | ||
|
||
Нет, вы не хотите попасть в такую неразбериху в какой-то момент. А возможно, никогда. Добавив в свой | ||
код `use strict`, вы укажете perl'у, что bareword <b>"hello"</b> в вашем коде недопустим, и | ||
избежите этой путаницы. | ||
|
||
```perl | ||
use strict; | ||
|
||
my $x = hello; | ||
print "$x\n"; | ||
``` | ||
|
||
Получим следуюшую ошибку: | ||
|
||
``` | ||
Bareword "hello" not allowed while "strict subs" in use at script.pl line 3. | ||
Execution of script.pl aborted due to compilation errors. | ||
``` | ||
|
||
## Правильное использование bareword'ов | ||
|
||
Существуют другие места, где bareword'ы могут использоваться, даже когда применено | ||
`use strict "subs"`. | ||
|
||
В первую очередь, имена подпрограмм, которые мы создаем, по сути являются bareword'ами. | ||
Допустим. | ||
|
||
Кроме того, когда мы указываем элемент хэша, мы можем поставить bareword в фигурных скобках, и слова | ||
по левую сторону толстой стрелки (=>) тоже могут обходиться без кавычек: | ||
|
||
```perl | ||
use strict; | ||
use warnings; | ||
|
||
my %h = ( name => 'Foo' ); | ||
|
||
print $h{name}, "\n"; | ||
``` | ||
|
||
В обоих случаях "name" - это bareword, но такое использование допустимо даже при включенном strict. | ||
|
||
|
Oops, something went wrong.