in reply to Sort Says "not numeric" then sorts numeric anyway?

And strict complains, because the arguments aren't numeric.
Actually, it's warnings that is complaining.
If you turn stricts off and keep warnings on, you get the message, which is, appropriately enough, a "warning."
When strict complains, it usually means that your program can't execute at all.
#!/usr/bin/perl -w use strict; my @x = qw( 1xxx 2xxx 300x 10xx ); @x = sort @x; print "default sort: @x\n"; @x = sort {local $^W; $a <=> $b} @x; print "numeric sort: @x\n";
Transforming the comparison elements with int($a) won't keep warnings silent either. Turning off warnings temporarily gets rid of the messages, but I wouldn't recommend it. Warnings are useful because they tell you that something is wrong and needs your attention.

Therefore I would go for the third solution.
However, your regex is not working. It seems to be doing something in your particular program, because the array was already sorted by the previous statement.
Try this.
@x = qw( 5xxx 2xxx 300x 10xx ); @x = sort {$a =~/^d+/ <=> $b =~/^d+/} @x; # WRONG print "regex sort: @x\n";
And your array is not sorted at all.
A better sorting should be
@x = qw( 5xxx 2xxx 300x 10xx ); @x = sort {my ($y) = $a =~/^(\d+)/; my ($z) = $b =~/^(\d+)/; $y <=> $z} @x; print "regex sort: @x\n";
_ _ _ _ (_|| | |(_|>< _|

Replies are listed 'Best First'.
Re: Re: Sort Says "not numeric" then sorts numeric anyway?
by Hofmator (Curate) on Feb 11, 2003 at 08:56 UTC
    You can simplify your - correctly working - sort a bit to: @x = sort { ($a =~/^(\d+)/)[0] <=> ($b =~/^(\d+)/)[0] } @x;The extra parens together with the access to the first element ([0]) force the regex into list context, which then returns the captured $1.

    As an additonal note: Depending on the size of the array, a Schwartzian Transform might be recommended instead.

    -- Hofmator

Re: Sort Says "not numeric" then sorts numeric anyway?
by Abigail-II (Bishop) on Feb 11, 2003 at 10:08 UTC
    Turning off warnings temporarily gets rid of the messages, but I wouldn't recommend it. Warnings are useful because they tell you that something is wrong and needs your attention.

    No, a warning doesn't say something is wrong. If something is wrong, you get an error. The warnings something may be wrong. Big difference. If the given case, sorting strings that starts with numbers numerically, the easiest, and IMO the right thing to do is to turn the warnings off.

    Going out of your way to avoid a warning to happen defeats the purpose of having a fine-grade, lexically tuneable warning system.

    Abigail