Operating System - HP-UX
1752730 Members
5645 Online
108789 Solutions
New Discussion юеВ

Perl script - can someone enlighten me?

 
SOLVED
Go to solution
Tony Walker
Frequent Advisor

Perl script - can someone enlighten me?

Hi Guys,

Here's the quick synopsis. I read a file which contains months and data. Using $month I add data to an array of this name as an element (i.e $month[1]=1). Lets say $month = Jan - if I foreach(@month) I get my elements OK. If I foreach(@Jan) I get nada!!

Please find a really cut down version of what I'm trying to do attached and the output. The file being opened contains the string 'Jan'.

Thanks for any help,

Tony
4 REPLIES 4
Tony Walker
Frequent Advisor

Re: Perl script - can someone enlighten me?

Forget that - I was being stoopid and referencing $month instead of $$month!

Now I have a different problem. I put all my months into an array a la @months=qw(blah blah) then I want to foreach each element in each month array like this:

foreach (@months){
foreach(@_){ #read as for each element in @Jan
do something
}
}
but this doesn't work. Any tips?

Thanks,

Tony
harry d brown jr
Honored Contributor

Re: Perl script - can someone enlighten me?

good source of date/time conversions:

http://pleac.sourceforge.net/pleac_perl/datesandtimes.html


live free or die
harry
Live Free or Die
Hein van den Heuvel
Honored Contributor

Re: Perl script - can someone enlighten me?

Tony, that second problem looks like 'self modifying code' to me. Loopign through somethign described by $_ but th eloop changes $_.

I would jst spend the extra four bytes and name your foreach return.

This works for me... is it what you wanted to achieve?

@aap=qw(een twee drie);
@noot=qw(vier vijf zes);
@mies=qw(zeven);
@months=qw(aap noot mies);
foreach $m (@months) {
print "$m\n";
foreach (@$m) {
print "m=$m _=$_\n";
}
}

H.Merijn Brand (procura
Honored Contributor
Solution

Re: Perl script - can someone enlighten me?

You want to use soft- or weak- reaferences.

DON'T!

Whenever you are tempted to do so, use a hash instead.

Your solution would be

my @jan = (1 .. 31);
my @feb = (1 .. 28);
:
foreach my $month (@month) {
foreach my $day (@$month) {
...
}
}

which is better to be done using a hash

my %month = (
jan => [ 1 .. 31 ],
feb => [ 1 .. 28],
);

foreach my $month (@month) {
foreach my $day (@{$month{$month}}) {
...
}
}

Enjoy, Have Fun! H.Merijn
Enjoy, Have FUN! H.Merijn