in reply to create arbitrarily named scalars
Solution: use an array!N_scalars("foo",5); --yields-- $foo_1 = ''; $foo_2 = ''; $foo_3 = ''; $foo_4 = ''; $foo_5 = '';
Whether you need 5 foos, or 50 foos, or 5,000,000 foos, @foo will hold them (as long as you have the necessary memory available). The only price you have to pay to use an array is remember that you start counting them at zero, not one. But most of the time you won't even have to count them, or even care how many you have:my @foo;
Now @file contains as many lines as are in the file foo.txt (as long as that file is the same directory that you ran that code in). Regardless of how many lines there are, these snippets will print them all:open FH, 'foo.txt' or die "$!: can't open foo.txt\n"; my @file = <FH>; close FH;
|
|
|
|
|
|
|
|
Solution: use an array! (an associative array)arb_scalars("alfa","bravo","charlie"); --yields-- $alpha = ''; $bravo = ''; $charlie = '';
Now i can find out what character belongs to 'charlie' like so:my %word = ( alpha => 'a', bravo => 'b', charlie => 'c', );
You don't need to create an arbitrary variable named $charlie. As a matter of fact, imagine having to pass 26 variables to a subroutine ... wouldn't you rather pass one hash instead? I would.print $word{'charlie'};
So, now that you know why you don't need 'arbitrary variables' in Perl, and you know that you can have them anyway ... why should you not use them? Well, my number one reason for not using them is because i think they are more trouble than they are worth. (passing one var vesus 26 ...)
Interestingly enough, PHP allows you to use 'arbitrary variables'. extract allows you to turn a hash's keys into varibles and compact will take a list of variables and create a new hash from them. You can do this in Perl1, but if you use strict in your script, then you have to declare the 'arbitrary variables' before you called explode (if such a sub existed in Perl). Having to declare them ahead of time isn't very 'arbitrary', and it is a major nuisance if you don't even need to know what they will be named.
1 I think that an explode for Perl would be pure abuse, but compact might be useful for creating objects with arbitrary attributes ... surely this is a already CPAN module ... ;)jeffa
L-LL-L--L-LL-L--L-LL-L-- -R--R-RR-R--R-RR-R--R-RR B--B--B--B--B--B--B--B-- H---H---H---H---H---H--- (the triplet paradiddle with high-hat)
|
|---|