|
Страница 1 из 1 [ Сообщений: 31 ] |
Автор |
Сообщение |
Proof
новый человек
|
|
Появилась проблема при написании скрипта.…
Как заставить скрипт записывать новое значение в форме обратно в файл?? Ничего не получается... Значение все никак не записывается.…
change.pl
Код: #!/usr/bin/perl
print "Content-type: text/html\n\n";
$url = '/home/folder/'; chdir $url; opendir DIR, $url or die "Can't opendir '$url': $!"; readdir DIR; @files = glob "*.txt";
foreach $a(@files){ open (data, $a); @data=<data>; close(data); print "$a<BR><form action=\"change2.pl\" method=\"post\"><textarea name=\"$a\">"; foreach $curline (@data) { print "$curline"; } print "</textarea><input type=\"submit\">\n"; print "</form><hr>\n";
}
closedir DIR; 2-ой файл скрипта (change2.pl): Код: #!/usr/bin/perl
print "Content-type: text/html\n\n";
$url = '/home/folder/'; open (TEMPLATE, ">$url$a"); print TEMPLATE $FORM{'$a'}; print "Done - <a href=\"change.pl\">Go Back</a>"; close(TEMPLATE);
Думаю, что вся проблема во 2ой части, т.к. не указано значение $a, но как его туда прописать, если оно меняется (см. foreach в 1ой части скрипта)….
Спасибо за внимание.…
|
|
 |
|
 |
Crazy
Модератор
|
|
Передавай значение $a в специальном hidden-поле с фиксированным именем. Это самый простой (но не единственный) способ.
_________________ We've got the big memory and the small memory. The small memory's to remember the small things and the big memory's to forget the big ones.
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Hidden поле это тоже часть формы, а поэтому, помоему, нету разницы между textarea и hidden... То есть, как я и не знал, как $a во 2ую часть перенести, так и не знаю.… А вот в этом то и проблема... Может я ошибаюсь, но с первого взгляда я не вижу как это дело можно прокрутить.….
|
|
 |
|
 |
Proof
новый человек
|
|
Proof,
Аааа... Сорри... Не прочитал ответ внимательно... Сейчас попробую...
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Ко мне чтото не доходит, как можно вообще любое значение формы из 1ой во 2ую часть передавать...
Может лучше части объеденить? Но тогда я не знаю, как обрабатывать запрос в одном скрипте.…
|
|
 |
|
 |
Crazy
Модератор
|
|
Proof писал(а): | Crazy, Ко мне чтото не доходит, как можно вообще любое значение формы из 1ой во 2ую часть передавать...
|
Код: $usedFiles = ""; foreach $a(@files){ open (data, $a); # … много поскипано print "</textarea><input type="submit">\n"; print "</form><hr>\n"; $usedFiles .= "|".$a; } print "<input type=hidden name=usedFiles value="$usedFiles">";
(квоинг сам добавишь)
Во второй части принимаешь usedFiles, сплитишь по символу "|" и получаешь список использованных тобой имен файлов. Дальше -- очевидно.
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Цитата: | Во второй части принимаешь usedFiles, сплитишь по символу "|" и получаешь список использованных тобой имен файлов. Дальше -- очевидно. |
Ну не знаю я как принимать usedFiles во 2ой части...
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Как я понимаю, если пользоваться этим способом, то я получаю "сырой список" во 2ой части... А ведь мне же надо, чтобы значение из поля 1 сохранялось в файл 1, 2 в 2, и т.д. А так определенность теряется.…
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Попробовал...
Код: #!/usr/bin/perl
print "Content-type: text/html\n\n";
$url = '/home/folder'; $usedFiles = ""; chdir $url; opendir DIR, $url or die "Can't opendir '$url': $!"; readdir DIR; @files = glob "*.txt";
foreach $a(@files){ open (data, $a); @data=<data>; close(data); print "$a<BR><form action=\"change2.pl\" method=\"post\"><textarea name=\"$a\">"; foreach $curline (@data) { print "$curline"; } print "</textarea><input type=\"submit\">\n"; print "</form><hr>\n"; $usedFiles .= "|".$a; } print "<input type=hidden name=usedFiles value=\"$usedFiles\">"; open (file, ">temp.txt"); print file "$usedFiles"; close file;
closedir DIR; 2ая: Код: #!/usr/bin/perl
print "Content-type: text/html\n\n";
$url = '/home/folder';
open (file, ">$url/temp.txt"); @files = split(/\|/,@files); close file;
foreach $a(@files){ open (TEMPLATE, ">$url/$a"); print TEMPLATE $FORM{'$a'}; print "Done - <a href=\"change.pl\">Go Back</a>"; close(TEMPLATE); }
Ноль результата.… Все делается, только за исключением записи в файлы.…
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Как могу, так и использую...
Пытаюсь все в файл записывать... Другого выхода не вижу.…
|
|
 |
|
 |
Crazy
Модератор
|
|
Пока что я никакого использования не вижу.
Но дело в другом. Чему, по твоему мнению, равно значение '$a', если собственно $a равно "foo"?  Советую проверить экспериментально -- эффект тебя удивит...
_________________ We've got the big memory and the small memory. The small memory's to remember the small things and the big memory's to forget the big ones.
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Дык, не знаю я, как $usedFiles использовать... Пытался - результаты сверху...
Цитата: | Чему, по твоему мнению, равно значение '$a', если собственно $a равно "foo"? Советую проверить экспериментально -- эффект тебя удивит |
Пробовал... Ничего не изменилось.…
|
|
 |
|
 |
Crazy
Модератор
|
|
Что пробовал?
Что не изменилось?
_________________ We've got the big memory and the small memory. The small memory's to remember the small things and the big memory's to forget the big ones.
|
|
 |
|
 |
Proof
новый человек
|
|
Может так лучше?:
Код: #!/usr/bin/perl
print "Content-type: text/html\n\n";
$url = '/home/folder; chdir $url; opendir DIR, $url or die "Can't opendir '$url': $!"; readdir DIR; @files = glob "*.txt";
foreach $a(@files){ open (data, $a); @data=<data>; close(data); print "$a<BR><form action=\"change.pl?action=new\" method=\"post\"><textarea name=\"$a\">"; foreach $curline (@data) { print "$curline"; } print "</textarea><input type=\"submit\">\n"; print "</form><hr>\n"; }
if ($action eq "new") { foreach $a(@files){ open (TEMPLATE, ">$a"); print TEMPLATE $FORM{'$a'}; print "Done"; close(TEMPLATE); } }
closedir DIR;
Но опять в файлы ничего не записывается... В чем дело то? Помогите.…
Спасибо...
|
|
 |
|
 |
Crazy
Модератор
|
|
Ты не провел эксперимент.
_________________ We've got the big memory and the small memory. The small memory's to remember the small things and the big memory's to forget the big ones.
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Спасибо за помощь.… Разобрался...
|
|
 |
|
 |
Proof
новый человек
|
|
Eще вопрос есть:
Как просканировать директорию на подкатегории, а не файлы? Фунцкия glob, вроде, не для этих целей.… Тоесть, чтобы эффект был как от glob (DIR, "*.txt"); только скрипт ищет не txt файлы, а директории...
|
|
 |
|
 |
Crazy
Модератор
|
|
glob'м ищешь все, а потом проверяешь, является ли очередное имя именем каталога.
_________________ We've got the big memory and the small memory. The small memory's to remember the small things and the big memory's to forget the big ones.
|
|
 |
|
 |
Proof
новый человек
|
|
C glob'ом разобрался... Только вот при выявлении каталогов появились проблемы:
Код: #!/usr/bin/perl require "settings.pl";
print "Content-Type: text/html\n\n";
$url = $ENV{'QUERY_STRING'}; $new_url = "$root/$url";
chdir $new_url; opendir DIR, $new_url or die "Can't opendir '$new_url': $!"; readdir DIR; @files = glob "*"; closedir DIR;
foreach $a(@files) { if ($a ne "*.shtml" && $a ne "*.txt") { if ($url eq "") { print "<p><a href=\"test.pl?$url$a\">$a</a>\n"; } else { print "<p><a href=\"test.pl?$url/$a\">$a</a>\n"; } } }
Скрипт вывод все: и директории, и файлы...
Вроде все описал, а он мои ограничения игнорирует.…
|
|
 |
|
 |
Proof
новый человек
|
|
Long,
А как же тогда высказать значение * в переменной? В моем случае.…
|
|
 |
|
 |
Long
SubAdmin Теоретик
|
|
можно, например, через регулярные выражения.
_________________ Мудрость не всегда приходит с возрастом. Бывает, что возраст приходит один.
|
|
 |
|
 |
Crazy
Модератор
|
|
Long писал(а): | мне кажется, что * в шаблоне имени файла не должнга работать  |
Работать то она работает.… Но вовсе не так, как думает гражданин Proof...
Вероятно, имелось в виду:
Код: if ($a !~ /\.(shtml|txt)$/) {
Кстати, Proof, твой скрипт делает вовсе не то, что ты думаешь... 
|
|
 |
|
 |
Proof
новый человек
|
|
Crazy,
Цитата: | if ($a !~ /\.(shtml|txt)$/) { |
Да.… Именно это.… Цитата: | Кстати, Proof, твой скрипт делает вовсе не то, что ты думаешь... |
 Это я уже давно догадался...
Это было смешно.…
|
|
 |
|
 |
MpaK999
участник
|
|
Зачем регуляркой? есть же grep (!)
_________________ :: metal kick ass ::
|
|
 |
|
 |
MpaK999
участник
|
|
эээ, ну без них никуда, но Код: if ($a !~ /\.(shtml|txt)$/) {
легче сделать grep'ом
_________________ :: metal kick ass ::
|
|
 |
|
 |
|
Страница 1 из 1 [ Сообщений: 31 ] |
Уровень доступа: Вы не можете начинать темы. Вы не можете отвечать на сообщения. Вы не можете редактировать свои сообщения. Вы не можете удалять свои сообщения. Вы не можете добавлять вложения.
|
|