LinuxForum.Fans
Тема

Массив в скриптах

Автор: Kettler 11 сообщений 3017 просмотров
#101264

Ребят может у кого есть готовые примеры по работе с массивами в скриптах?
Особенно интересует выборка.

#101398
Kettler написал:
Ребят может у кого есть готовые примеры по работе с массивами в скриптах?
Особенно интересует выборка.

вам именно массивы нужны? или строки пойдут?

вот в bash'е:

text
Arrays
       Bash  provides one-dimensional array variables.  Any variable may be used as an array; the declare builtin
       will explicitly declare an array.  There is no maximum limit on the size of an array, nor any  requirement
       that members be indexed or assigned contiguously.  Arrays are indexed using integers and are zero-based.

An array is created automatically if any variable is assigned to using the syntax name[subscript]=value. The subscript is treated as an arithmetic expression that must evaluate to a number greater than or equal to zero. To explicitly declare an array, use declare -a name (see SHELL BUILTIN COMMANDS below). declare -a name[subscript] is also accepted; the subscript is ignored. Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array.

Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value is of the form [subscript]=string. Only string is required. If the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero. This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above.

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid con‐ flicts with pathname expansion. If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[звёздочка]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters * and @ (see Special Parameters above). ${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is * or @, the expansion is the number of ele‐ ments in the array. Referencing an array variable without a subscript is equivalent to referencing ele‐ ment zero.

The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript. Care must be taken to avoid unwanted side effects caused by filename generation. unset name, where name is an array, or unset name[subscript], where subscript is * or @, removes the entire array.

The declare, local, and readonly builtins each accept a -a option to specify an array. The read builtin accepts a -a option to assign a list of words read from the standard input to an array. The set and declare builtins display array values in a way that allows them to be reused as assignments.

[console]doc@bx:~/tests$ declare array X
doc@bx:~/tests$ X['other']="другое"
doc@bx:~/tests$ echo ${X[звёздочка]}
другое
doc@bx:~/tests$ echo ${X[@]}
другое
doc@bx:~/tests$ X[1]="один"
doc@bx:~/tests$ X[2]="два"
doc@bx:~/tests$ X[3]="три"
doc@bx:~/tests$ echo ${X[звёздочка]}
другое один два три
doc@bx:~/tests$ echo ${X[2]}
два
doc@bx:~/tests$ echo ${X['other']}
другое
[/console]
в sed массивов нету ;-(
в gawk есть, но я не использую gawk.
в пайтоне есть куча всего интересного (кортёжи, словари и прочее)
в C массивов нет, есть оператор []. В C++ этот оператор можно перезагружать, что позволяет сделать имитацию массивов. Что вас конкретно интересует?

ЗЫЖ звёздочку(*) я заменил на "звёздочка"

#101403

ЗЫЖ примечание: в обычной shell как раз массивов-то и нету :(
потому скрипты с массивами НЕ переносимы, и не везде будут работать! Потому в начале скрипта пишите

text
#!/bin/bash

(в большинстве систем это не играет роли. Но вот в убунте, по слухам, какой-то свой dash, как и в Debian'е. Кроме того возможны проблемы в BSD)
Я вас предупредил...

#101407

ззыж в php массивы есть. очень хорошие. рекомендую (php вообще ИМХО самый лучший из скриптовых ЯП).
примеры нужны?

#101876
drBatty написал:
ззыж в php массивы есть. очень хорошие. рекомендую (php вообще ИМХО самый лучший из скриптовых ЯП).
примеры нужны?

Для каких целей он самый лучший из скриптовых?

#101890

drBatty, незнаю как насчет лучшего, но для скриптов, как замену bash, использовать можно =)

#101991

elve,
можно узнать, как? Пример?

#102051
Hvzh написал:
Для каких целей он самый лучший из скриптовых?

для общих целей. bash очень медленный. если быстродействие не играет роли (а так обычно и бывает, т.к. 80-95% времени занимают разные конструкции на C/C++), то и bash неплох.

Hvzh написал:
можно узнать, как? Пример?

[console]doc@bx:~$ cat ./helloword.php
#!/usr/bin/php

<?php
echo "привет, Мир!"
?>

doc@bx:~$ ./helloword.php

привет, Мир!
[/console]

#102052

у нас на повестке дня массивы. Извольте-с:
[console]doc@bx:~$ cat ./helloword.php
#!/usr/bin/php
<?php
$a = array("a", "b", "c");
foreach($a as $e)
echo $e . "\n";
?>
doc@bx:~$ ./helloword.php
a
b
c
[/console]

#103404

Спасибо "drBatty" за примеры просто 3 дня в бане отсиживал :D .

Войдите или зарегистрируйтесь, чтобы ответить.