SaltyBall said:
Here we have a date array like this
@array=(2006-01-03, 2006-03-24, 2005-01-06);
when I use
sort(@array)
it did not sort correctly, the month and date was not sort, I think it
is the "-" make the sort fail, what is the correct way to sort this array?
From a later posting, I see that you understand that sort(@array) is
not an "in-place" sort and will not modify the contents of @array.
However, I think you might have missed what other posters were trying
to tell you about the "-":
You seem to think it is part of a string, but Perl is treating it a
the subtraction operator. In other words, when you write:
2006-01-03
Perl thinks you meant:
2006 minus 1 minus 3 ==> which equals 2002.
To illustrate this, if you change the line of code:
@array=(2006-01-03, 2006-03-24, 2005-01-06);
to:
print join(' ', 2006-01-03, 2006-03-24, 2005-01-06);
you'll see that the output is not:
2006-01-03 2006-03-24 2005-01-06
as you thought, but rather:
2002 1979 1998
which is the result of performing the subtraction on the year values.
You probably meant to treat the values as strings and write:
@array=("2006-01-03", "2006-03-24", "2005-01-06");
and then later:
@array = sort(@array);
I also strongly recommend putting the following two lines near the
top of your script:
use strict;
use warnings;
You might not realize it, but those two lines can immediately catch
up to about 90% of the errors you make. And they'll tell you the exact
line number the errors are on without you needing to spend fifteen
minutes trying to hunt each bug down.
Seriously, I recommend either including those two "use" lines, or
else consider using another programming language altogether. Not using
those two lines allows for so many things to go wrong (that would have
otherwise been easily caught and reported) that it's usually not really
worth programming in Perl without them. (I feel that this is still
true whether you're a beginner or an advanced Perl programmer.)
I hope this helps!
-- Jean-Luc
perl -le "print(pack'B*','0'.unpack'B*',pack'w*',
5592691776,37562575106519616,25926642752,354130435682904)"