[perl] Variabele variabelen aanmaken

Pagina: 1
Acties:

  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
Hallo,

Ik heb een tabel met allemaal instellingen aangemaakt in mysql. Ik wil al deze instellingen als variabele hebben in een perl script. In php heb ik dit (even gemaakt om duidelijk te maken wat ik bedoel):
PHP:
1
2
3
4
5
$sql_sel = "SELECT * FROM dir_protect_options";
$res_sel = ExecSQL($sql_sel);

while($row_sel = mysql_fetch_object($res_sel))
    $$row_sel->option_name = $row_sel->option_value;

Is er een mogelijkheid om dit ook in perl te doen?

  • Woy
  • Registratie: April 2000
  • Niet online

Woy

Moderator Devschuur®
Je hebt in perl geloof ik standaard Hash tables. Die kan je hier mooi voor gebruiken

“Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.”


  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
Ik heb snel even gezocht (google: perl hash tables) maar kan niet echt iets bruikbaars over hashtables vinden. Kun je misschien wat meer van de sluier opliften :)

Zijn hashies een soort van arrays?

[ Voor 14% gewijzigd door Slagroom op 17-06-2003 11:01 ]


  • oVRoM
  • Registratie: Juli 2000
  • Niet online
Uit Roberts Perl Tutorial:
Very, very useful. First, a quick recap on arrays. Arrays are an ordered list of scalar variables, which you access by their index number starting at 0. The elements in arrays always stay in the same order.

Hashes are a list of scalars, but instead of being accessed by index number, they are accessed by a key. The tables below illustrate the point:
Afbeeldingslocatie: http://www.christinaricci.info/upload/hash.png
So if we want 'Belgium' from @myarray and also from %myhash , it'll be:

print "$myarray[1]";
print "$myhash{'BE'}";
Notice that the $ prefix
is used, because it is a scalar variable. Despite the fact it is part of a
list, it is still a scalar variable. The hash syntax is simply to use braces { } instead of square brackets.

So why use hashes ? When you want to look something up by a keyword. Suppose we wanted to create a program which returns the name of the country when given a country code. We'd input ES, and the program would come back with Spain.

You could do it with arrays. It would be messy however. One possible approach:

1. create @country , and give it values such as 'ES,Spain'
2. Itierate over the entire array and
3. split each element of the array, and check the first result to see if it matches the input
4. If so, return the index

@countries=('NL,The Netherlands','BE,Belgium','DE,Germany','MC,Monaco','ES,Spain');

print "Enter the country code:";
chop ($find=<STDIN>);

foreach (@countries) {
($code,$name)=split /,/;
if ($find=~/$code/i) {
print "$name has the code $code\n";
}
}
Complex and slow. We could also store a reference to another array in each element of @countries , but that is not efficient. Whatever way we choose,
you still need to search the whole thing. And what if @countries is a big array ? See how much easier a hash is:


A Hash in Action

%countries=('NL','The Netherlands','BE','Belgium','DE','Germany','MC','Monaco','ES','Spain');

print "Enter the country code:";
chop ($find=<STDIN>);

$find=~tr/a-z/A-Z/;
print "$countries{$find} has the code $find\n";
Very easy. All we need to do is make sure everything is in uppercase with tr and we are there. Notice the way %countries is defined - exactly the same as a normal array,
except that the values are put into the hash in key/value pairs.

  • oVRoM
  • Registratie: Juli 2000
  • Niet online
Slagroom schreef op 17 juni 2003 @ 10:59:
Zijn hashies een soort van arrays?
Yep, hashes heten ook wel Associative Arrays.

  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
Perl:
1
2
3
4
5
6
7
8
9
10
$str_hash = "";

$sth = $dbh->prepare("SELECT option_name, option_value FROM dir_protect_options");
$sth->execute;

while (@data = $sth->fetchrow_array()) {
    $str_hash .= "'".$data[0]."','".$data[1]."',";
}

%options = ($str_hash);


Kan ik het dan op zo'n soort manier doen? Of zit ik dan helemaal kompleet fout (dat verwacht ik wel).

  • thomaske
  • Registratie: Juni 2000
  • Laatst online: 14-07 14:28

thomaske

» » » » » »

Even een kleine voetnoot over variabele variabelen

kvdveer:
Mensen die dit soort constructies gebruiken dienen echter standrechtelijk geexecuteerd te worden. De mensen die deze constructie hebben verzonnen dienen met een kaasschaaf teruggebracht te worden tot een formaat van 3 inch in het vierkant.

Brusselmans: "Continuïteit bestaat niet, tenzij in zinloze vorm. Iets wat continu is, is obsessief, dus ziekelijk, dus oninteressant, dus zinloos."


  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
thomaske schreef op 17 June 2003 @ 11:21:
Even een kleine voetnoot over variabele variabelen

kvdveer:
[...]
Ok, maar zou je mij eens willen vertellen waarom het gebruik maken van variabele variabelen zo verkeerd is? Zoveel performence verlies? Groot geheugen gebruik? Wat?

  • smoking2000
  • Registratie: September 2001
  • Laatst online: 22-08 06:21

smoking2000

DPC-Crew

dpkg-reconfigure reality

Perl:
1
2
3
4
5
6
7
8
9
10
my %options;

my $sth = $dbh->prepare("SELECT option_name, option_value FROM dir_protect_options");
$sth->execute;

while (my @data = $sth->fetchrow) {
           $options{$data[0]} = $data[2];
}

$sth->finish;


Zo zou ik het doen..

[ Voor 16% gewijzigd door smoking2000 op 17-06-2003 11:27 ]

| [Folding@Home] Announce: Client monitor voor Linux (fci) | fci-1.8.4 | Fatal Error Group |


  • Woy
  • Registratie: April 2000
  • Niet online

Woy

Moderator Devschuur®
Slagroom schreef op 17 June 2003 @ 11:23:
[...]

Ok, maar zou je mij eens willen vertellen waarom het gebruik maken van variabele variabelen zo verkeerd is? Zoveel performence verlies? Groot geheugen gebruik? Wat?
Omdat je totaal het overzicht verliest. Je weet totaal niet meer wat er met je variabelen gebeurt en welke er nou precies bestaan. Voor dit doel moet je altijd Array's, List's, HashTables of een andere vorm van een collection gebruiken. Deze zijn hiervoor bedoeld en je kiest voor elk geval het type collection die voor die situatie het beste is.

“Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.”


  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
rwb schreef op 17 June 2003 @ 11:33:
[...]


Omdat je totaal het overzicht verliest. Je weet totaal niet meer wat er met je variabelen gebeurt en welke er nou precies bestaan. Voor dit doel moet je altijd Array's, List's, HashTables of een andere vorm van een collection gebruiken. Deze zijn hiervoor bedoeld en je kiest voor elk geval het type collection die voor die situatie het beste is.
Ok, klopt. Wat je zegt is waar. Het oogt netter en je kunt beter door je code's ploeteren. Maar is er ook een verschil in performance?

---
Nog even een beetje offtopic maar is het verstandig om, wanneer je een file handler gebruikt, deze van te voren de declareren met my?

[ Voor 15% gewijzigd door Slagroom op 17-06-2003 11:43 ]


  • Woy
  • Registratie: April 2000
  • Niet online

Woy

Moderator Devschuur®
Slagroom schreef op 17 juni 2003 @ 11:38:
[...]


Ok, klopt. Wat je zegt is waar. Het oogt netter en je kunt beter door je code's ploeteren. Maar is er ook een verschil in performance?
Dat ligt er een beetje aan hoe het in PHP geimplementeerd is. Ik werk zelf nooit met PHP. Maar een hashtable is in dit soort gevallen meestal wel de meest optimale implementatie van een collection. Als je weet hoeveel elementen je hebt en je moet hier altijd van 0 tot n doorheen lopen kan je weer beter een array gebruiken. Als je hier wat meer over wilt weten moet je even op google naar Data Structures zoeken ofzo. Want er zijn nogal wat vershillende mogelijkheden

“Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.”


  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
Die hash tables zijn wel tjill heb ik nu gemerkt. Ga ik in het vorvolgs ook soortgelijks met php doen.

Alles werkt nu, bedankt iedereen!

  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
Nog één vraagje, wanneer ik dit doe krijg ik een systax error. Waarschijnlijk heeft het te maken met die \" en " maar ik weet niet hoe ik het wel moet doen. Iemand:

Perl:
1
2
3
4
5
6
open FH, "> ".$options{'dir_protect'}."/.htaccess";
print FH "AuthType Basic\n"
print FH "\"Leden\"\n"
print FH "AuthUserFile \"".$options{'dir_protect'}."/.htpasswd\"\n\n"
print FH "Require valid-user"
close FH;

Verwijderd

zou je niet elke regel afsluiten met een ;?

  • oVRoM
  • Registratie: Juli 2000
  • Niet online
Perl:
1
open FH, "> ".$options{'dir_protect'}."/.htaccess";

Weet niet of dit werkt maar ik zou
Perl:
1
open FH, ">$options{'dir_protect'}/.htaccess";

gebruiken

Edit:
Zelfde voor
Perl:
1
print FH "AuthUserFile \"".$options{'dir_protect'}."/.htpasswd\"\n\n"

Ik zou:
Perl:
1
print FH "AuthUserFile \"$options{'dir_protect'}/.htpasswd\"\n\n";

gebruiken.

Edit 2: Hmm zie dat het wel werkt op jou manier. Prima :) maar ik vind het niet heel duidelijk. Maar das dus persoonlijk ;)

[ Voor 94% gewijzigd door oVRoM op 18-06-2003 16:35 ]


  • Slagroom
  • Registratie: Juni 2001
  • Laatst online: 15-06 17:30
Verwijderd schreef op 18 juni 2003 @ 16:04:
zou je niet elke regel afsluiten met een ;?
Dat was het! Bedankt! Stomme fout!

[ Voor 4% gewijzigd door Slagroom op 18-06-2003 18:17 ]

Pagina: 1