Home > Archive > PERL Beginners > June 2005 > @array =to=> $array
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
@array =to=> $array
|
|
| shoker@xtra.co.nz 2005-06-10, 3:56 am |
| Hi All
Prob: I want to convert all the elememts of an array to ascalor variable that I can use latter on in my code
e.g.
my @array=qw/balli johney bobby/;
now here i need 3 different variable with the above values i.e.
my $name1=balli ;
my $name2=johney ;
my $name3=bobby ;
Soln so far:
my ($i) ;
for ($i=0; $i<@array;$i++)
{
$name=$array[$i] ; # lost here is to how to have different $name each time also how can make these $names available out side the block as iam using strict. I am sure there is acleaver way of doing this. need help!!!!!
}
-Bobby
| |
| John W. Krahn 2005-06-10, 3:56 am |
| shoker@xtra.co.nz wrote:
> Hi All
Hello,
> Prob: I want to convert all the elememts of an array to ascalor variable that I can use latter on in my code
Each element of an array *is* a scalar so why do you think you need to do this?
> e.g.
>
> my @array=qw/balli johney bobby/;
> now here i need 3 different variable with the above values i.e.
> my $name1=balli ;
> my $name2=johney ;
> my $name3=bobby ;
>
> Soln so far:
>
> my ($i) ;
> for ($i=0; $i<@array;$i++)
> {
> $name=$array[$i] ; # lost here is to how to have different $name each time also how can make these $names available out side the block as iam using strict. I am sure there is acleaver way of doing this. need help!!!!!
> }
my ( $name1, $name2, $name3 ) = @array;
John
--
use Perl;
program
fulfillment
| |
| Lawrence Statton 2005-06-10, 3:56 am |
| > Hi All
>
> Prob: I want to convert all the elememts of an array to ascalor variable that
> I can use latter on in my code
> e.g.
>
> my @array=qw/balli johney bobby/;
> now here i need 3 different variable with the above values i.e.
> my $name1=balli ;
> my $name2=johney ;
> my $name3=bobby ;
>
No. You need very much *NOT* to do that, since you already have it
built-in to Perl:
$array[0] = 'balli';
$array[1] = 'johney';
$array[2] = 'bobby';
Problem solved.
ANY time you see in your code something of the form
$foo1, $foo2, $foo3 ....
you should be using an array.
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Lawrence Statton - lawrenabae@abaluon.abaom s/aba/c/g
Computer software consists of only two components: ones and
zeros, in roughly equal proportions. All that is required is to
sort them into the correct order.
| |
| Pablo Wolter 2005-06-10, 3:56 am |
| shoker@xtra.co.nz wrote:
> Hi All
>
>Prob: I want to convert all the elememts of an array to ascalor variable that I can use latter on in my code
>e.g.
>
>my @array=qw/balli johney bobby/;
>now here i need 3 different variable with the above values i.e.
>my $name1=balli ;
>my $name2=johney ;
>my $name3=bobby ;
>
>Soln so far:
>
>my ($i) ;
>for ($i=0; $i<@array;$i++)
>{
>$name=$array[$i] ; # lost here is to how to have different $name each time also how can make these
>
my $i;
for ($i=0; $i<@arrayl $i++) {
$name$i=$array[$i];
}
That way you don't need to know in advance how many $name variables you
need.
>$names available out side the block as iam using strict. I am sure there is acleaver way of doing this. need help!!!!!
>}
>
>-Bobby
>
>
>
>
>
| |
| Wiggins d'Anconia 2005-06-10, 3:56 am |
| Pablo Wolter wrote:
> shoker@xtra.co.nz wrote:
>
>
>
> my $i;
> for ($i=0; $i<@arrayl $i++) {
> $name$i=$array[$i];
> }
>
> That way you don't need to know in advance how many $name variables you
> need.
>
After fixing the typo at the end of @array, I still end up with:
"Scalar found where operator expected at ./test.pl line 16, near "$name$i"
(Missing operator before $i?)
syntax error at ./test.pl line 16, near "$name$i"
Execution of ./test.pl aborted due to compilation errors."
Make sure to test before posting.
http://danconia.org
[snip]
| |
| Lawrence Statton 2005-06-10, 3:56 am |
| > shoker@xtra.co.nz wrote:
>
> t I can use latter on in my code
> lso how can make these
> my $i;
> for ($i=0; $i<@arrayl $i++) {
> $name$i=$array[$i];
> }
>
> That way you don't need to know in advance how many $name variables you
> need.
>
NO, NO, NO, NO, NO!!!!!!!!!!!!!!!!!
First: Your code doesn't even work.
Second: It is not actually SOLVING anything.
variables of the form
$name0, $name1, $name2
.... do not provide **ANY** functional difference from
$array[0], $array[1], and $array[2]
Write that on the blackboard fifty times.
That is to say: $array[0] is a first-class citizen, just as good as
$name0 -- iterating in the worst possible way[1] across an array to
create copies of the data provides NO additional functionality to the
code.
I suspect if the original poster could read and write English he
(she?) would be able to explain what was really needed.
There *are* times when exploding an array into a series of separately
named scalars *does* make sense.
Think how stupid the following is:
my @array;
($array[0], $array[1], $array[2], $array[3],
$array[4], $array[5], $array[6], $array[7], $array[8] ) = localtime(time);
But, if we rewrite it thusly...
my ($second, $minute, $hour,
$month_day, $month, $year,
$w day, $yearday, $isdst ) = localtime(time);
....the phrase makes sense. You are expanding the list of nine data
returned by localtime into convenient mnemonic variables.
(Getting further afield: I would probably never do THAT either -- if I
have a series of nine things that are tightly coupled, I would want
some better data structure to hold them. A hash or hashref, would be
perfect.)
my $localtime;
@$localtime{qw / second minute hour mday month year w day yearday isdst /} =
localtime(time);
[1] A style nit:
Write Perl, not C.
If you DO need to iterate across all the indices for an array ( rarely
necessary if you have designed your data correctly ) do it right:
my @person = ( qw / Freddy Mary Georgetta Loretta Fred Lawrence / );
##
## UNBEARABLY LAME C
##
for ( my $index = 0 ; $index < @person ; $index ++ ) {
print "unbearably bad $person[$index]\n";
}
##
## MERELY BAD PERL
##
for my $index ( 0 .. $#person ) {
print "merely bad $person[$index]\n";
}
##
## GETTING INTO THE PERL STATE OF MIND
##
for my $person (@person) {
print "Hello $person\n";
}
Note that of the three techniques, the last is the only one that will
work for all values of $[ (of course, anyone who sets $[ to any
nonzero value deserves hot pokers in the eyes.)
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Lawrence Statton - lawrenabae@abaluon.abaom s/aba/c/g
Computer software consists of only two components: ones and
zeros, in roughly equal proportions. All that is required is to
sort them into the correct order.
| |
| Dave Gray 2005-06-10, 8:55 pm |
| > my $localtime;
> @$localtime{qw / second minute hour mday month year w day yearday isdst=
/} =3D
> localtime(time);
>=20
> [1] A style nit:
Speaking of nitpicks:
my %localtime;
> If you DO need to iterate across all the indices for an array ( rarely
> necessary if you have designed your data correctly ) do it right:
>=20
> my @person =3D ( qw / Freddy Mary Georgetta Loretta Fred Lawrence / );
>=20
> ##
> ## UNBEARABLY LAME C
> ##
>=20
> for ( my $index =3D 0 ; $index < @person ; $index ++ ) {
> print "unbearably bad $person[$index]\n";
> }
>=20
> ##
> ## MERELY BAD PERL
> ##
>=20
> for my $index ( 0 .. $#person ) {
> print "merely bad $person[$index]\n";
> }
This is not Bad Perl. This is a solution to a problem that the
following code will not solve. Sometimes you need $index, sometimes
you don't.
> ##
> ## GETTING INTO THE PERL STATE OF MIND
> ##
>=20
> for my $person (@person) {
> print "Hello $person\n";
> }
| |
| Lawrence Statton 2005-06-10, 8:55 pm |
| > > my $localtime;
> } =
>
> Speaking of nitpicks:
> my %localtime;
Assuming you are suggesting making that change, I'd reccomend against
it, unless you wish to elicit the following error:
Global symbol "$localtime" requires explicit package name at /tmp/try line 12.
Global symbol "$localtime" requires explicit package name at /tmp/try line 14.
Execution of /tmp/try aborted due to compilation errors.
However, leaving it as:
my $localtime;
@$localtime{qw / second minute hour mday month
year w day yearday isdst /} = localtime(time);
print Dumper $localtime;
Will result in the following output:
$VAR1 = {
'w day' => 5,
'hour' => 11,
'month' => 5,
'second' => 25,
'isdst' => 1,
'minute' => 27,
'yearday' => 160,
'mday' => 10,
'year' => 105
};
>
> This is not Bad Perl. This is a solution to a problem that the
> following code will not solve. Sometimes you need $index, sometimes
> you don't.
I concede the point -- it is not Bad Perl. It is Bad Programming, using
Perl as the platform for badness :)
The subtle point I was trying to make was: Needing $index is
frequently a sign of bad data design. Not always, mind you -- but it
should be a flashing yellow light meaning "am I doing something lame
here?"
>
>
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Lawrence Statton - lawrenabae@abaluon.abaom s/aba/c/g
Computer software consists of only two components: ones and
zeros, in roughly equal proportions. All that is required is to
sort them into the correct order.
| |
| Dave Gray 2005-06-10, 8:55 pm |
| On 6/10/05, Lawrence Statton <lawrence@cluon.com> wrote:
sdst /[color=darkred]
>=20
> Assuming you are suggesting making that change, I'd reccomend against
> it, unless you wish to elicit the following error:
>=20
> Global symbol "$localtime" requires explicit package name at /tmp/try lin=
e 12.
> Global symbol "$localtime" requires explicit package name at /tmp/try lin=
e 14.
> Execution of /tmp/try aborted due to compilation errors.
Huh. So it does... that doesn't look like it's making a reference,
though. I think I would write that as @{$localtime}{ ... } for
clarity.
> Computer software consists of only two components: ones and
> zeros, in roughly equal proportions. All that is required is to
> sort them into the correct order.
Heh. I like that.
| |
| Lawrence Statton 2005-06-10, 8:55 pm |
| > Huh. So it does... that doesn't look like it's making a reference,
> though. I think I would write that as @{$localtime}{ ... } for
> clarity.
>
I only got out my "snippy" voice because it will be a snowy day here
when I post example code to the list that hasn't actually been tested.
It does not boost ones reputation as a source of Good Advice to give
non-functioning examples, or suggest breaking known-working code.
As to the clarity question. To my eyes, I find spurious {} tend to
diminish rather than enhance, especially in common idioms, but I am
wiling to accept it as a question of taste.
Last night, my associate Will remarked, "You are replying to someone
who is by simple arrays with an example of a hashref-slice?"
And I responded: "Hash slices (and their reference form) are such a
wonderfully useful tool that they should be taught early and often."
To that end: a humble example...
------------- begin perl code --------------------------
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper qw(Dumper);
#
# Suppose we want to collect a little information
# about a person
#
my %person;
## brute force technique
# Gets the job done. Not very pretty.
$person{first_name} = 'Lawrence';
$person{last_name} = 'Statton';
$person{ocupation} = 'Perl Hacker';
$person{city} = 'Guadalajara';
$person{country} = 'Mexico';
## Slightly easier on the fingers version:
%person = ( first_name => 'Lawrence',
last_name => 'Statton',
occupation => 'Perl Hacker',
city => 'Guadalajara',
country => 'Mexico' );
## Here is the hash slice notation
@person{ qw / first_name last_name occupation city country / } =
( 'Lawrence', 'Statton', 'Perl Hacker', 'Guadalajara', 'Mexico' );
## what can I do with that?
## suppose you have a line from a text file of the form
my $line = 'Lawrence:Statton:Perl Hacker:Guadalajara:Mexico';
@person{ qw / first_name last_name occupation city country/ } = split(':', $line );
##
## NOW - let's do that whole thing, instead of using a hash (%person) we'll
## use a hashref $person
##
my $person;
$person->{first_name} = 'Lawrence';
$person->{last_name} = 'Statton';
$person->{ocupation} = 'Perl Hacker';
$person->{city} = 'Guadalajara';
$person->{country} = 'Mexico';
# or ...
%$person = ( first_name => 'Lawrence',
last_name => 'Statton',
occupation => 'Perl Hacker',
city => 'Guadalajara',
country => 'Mexico' );
# even better ...
$person = { first_name => 'Lawrence',
last_name => 'Statton',
occupation => 'Perl Hacker',
city => 'Guadalajara',
country => 'Mexico' };
## now, combining the hashref with the hash-slice notation, we get:
@$person{ qw / first_name last_name occupation city country/ } = split(':', $line ); # creates $person = { ... }
## compare it to a duplicate of the hash-slice --> hash notation
@person{ qw / first_name last_name occupation city country/ } = split(':', $line ); # creates %person = ( ... )
-------------- end perl code ---------------------------
>
> Heh. I like that.
Thanks. A friend and I came up with that in a late-night debugging
session in 1985. I think it was the same sleep-deprivation-induced
stupor that produced the spoonerism 'iso-optilator'.
| |
| Dave Gray 2005-06-10, 8:55 pm |
| On 6/10/05, Lawrence Statton <lawrence@cluon.com> wrote:
>=20
> As to the clarity question. To my eyes, I find spurious {} tend to
> diminish rather than enhance, especially in common idioms, but I am
> wiling to accept it as a question of taste.
When I mentioned clarity, I was referring to forcing precedence, even
if it does not change the effect. I am, however, willing to accept the
use of the word "spurious" as a question of opinion ;)
|
|
|
|
|