Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Sorting The Date format Values without using any perl modules.

by jesuashok (Curate)
on Dec 26, 2005 at 14:40 UTC ( #519147=perlquestion: print w/ replies, xml ) Need Help??
jesuashok has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I want to sort the Date type values which is in array.

my @list = ( '2005-12-01' , '2005-11-02' , '2005-12-07');

I wanto sort @list. But without using any Date Sort modules. But we I can use perl's sort function.

How that can be done.

NOTE:

Please don't use split also.

"Keep pouring your ideas"

Comment on Sorting The Date format Values without using any perl modules.
Re: Sorting The Date format Values without using any perl modules.
by Corion (Pope) on Dec 26, 2005 at 14:49 UTC

    What did you try so far? Have you looked at Perls sort function? The documentation is available via perldoc -f sort, or perldoc sort. Did you try simply using sort? Please don't ask us to do your homework!

    The sort documentation mentions the following example:

    @articles = sort {$a cmp $b} @files;

    Maybe you can adapt it to your needs.

      Hi,

      Please look into the above code. I tried using sort also. But then I am facing the Issue.

      #!/usr/bin/perl + + @sort = ( '05-11-2006', '01-01-2005' , '04-12-2005' , '22-03-2005'); + + foreach (sort @sort) { print ":$_:\n"; }
      OUTPUT: :01-01-2005: :04-12-2005: :05-11-2006: :22-03-2005:
      Please Note the output carefully. I want to that to be sorted. Please provide me your Idea.

      "Keep pouring your ideas"

        Did you read my node? Did you read the sort documentation? Did you look at my example and look how you could adapt it to your needs?

        Please take another look at the sort documentation. Please look at my example (taken from there) and see how you can adapt it to what you need.

        @articles = sort {$a cmp $b} @files;
        To add to Corion's comment the arrays in your original post and in your follow up are different.

        It's hard to help if the question keeps moving!

        update: the following is wrong :-(

        Each element in your follow up array is the reverse of those in the origninal. (There's a hint in there!)

        With that observation and another look at the docs I was able to sort the array in the order you're looking for using the method suggested by Corion.

        You didn't say my $sort = (... either.

        update 2:

        Pursuing the reverse theme, perhaps you could consider an intermediate step:

        #!/bin/perl5 use strict; use warnings; use Data::Dumper; my @sort = qw( 05-11-2006 01-01-2005 04-12-2005 22-03-2005 ); my @reversed = map { join '', substr($_, 6), substr($_, 3,2), substr($_, 0,2) } @sort; print Dumper(\@reversed); __DATA__ ---------- Capture Output ---------- > "C:\Perl\bin\perl.exe" _new.pl $VAR1 = [ '20061105', '20050101', '20051204', '20050322' ]; > Terminated with exit code 0.

        Now you changed your requirements in the middle - which incidentally is mostly annoying. If they're as in the OP, then my reply still applies.

        Or else you will have to provide a suitable sort sub, possibly exploiting one of the various sorting techniques often references here and elsewhere. Try checking for example:

        from the Tutorials section. A recent post of mine using a form of Guttman-Rossler is this. In this case you should have fixed length fields and it should be even easier for you to recover the original data with a single substr.

Re: Sorting The Date format Values without using any perl modules.
by john_oshea (Priest) on Dec 26, 2005 at 15:02 UTC

    Use Time::Local to convert the dates to 'seconds since epoch' values, sort them, then use localtime or gmtime to convert back to a human-readable format. This assumes you want the dates sorted chronologically, and not by month or day number...

    Or does that count as a 'Date Sort' module? ;-)

Re: Sorting The Date format Values without using any perl modules.
by wfsp (Abbot) on Dec 26, 2005 at 15:10 UTC
Re: Sorting The Date format Values without using any perl modules.
by eric256 (Parson) on Dec 26, 2005 at 16:14 UTC

    This answer is intentionaly vague since your data changed twice and I have no idea which to use, and it appears this is some sort of homework because of the strange no split suggestion. If you can't use split, then look for some way to split a string without using split. One way would be to use substr instead.

    my $test = "Hello World"; my $new = substr($test, 6,5) . "-" . substr($test,0,5); print $new;


    ___________
    Eric Hodges $_='y==QAe=e?y==QG@>@?iy==QVq?f?=a@iG?=QQ=Q?9'; s/(.)/ord($1)-50/eigs;tr/6123457/- \/|\\\_\n/;print;
Re: Sorting The Date format Values without using any perl modules.
by jkeenan1 (Chaplain) on Dec 26, 2005 at 16:23 UTC
    If I understand you correctly, you have a list of dates, each of which is formatted YYYY-MM-DD. Your objective is to reformat each string to DD-MM-YYYY and then to output them in date order.

    The solution will probably involve sorting the YYYY-MM-DD elements alphabetically (which works out to chronologically in this case), mapping each element of the sorted list to a hash where the value is the date's index position in the sorted list. But at that point you'll have to use split to reformat the original strings before pushing them onto a new list in an order specified by the hash, which you will be using as a look-up table.

    So I don't understand why you're forbidden to use split as part of the solution. Please clarify.

    Jim Keenan

      But at that point you'll have to use split to reformat the original strings before pushing them onto a new list in an order specified by the hash, which you will be using as a look-up table.

      Well, split is indeed the most natural tool to do that, and the one I would use, and to stress it once more: there's really no good reason why one should not use it! (or else the OP should provide one!) But as usual TMTWOTDI: see for example the alternative I offer in this reply - it's even actually shorter...

Re: Sorting The Date format Values without using any perl modules.
by CountZero (Bishop) on Dec 26, 2005 at 19:52 UTC
    Pray, please tell us why you are not allowed to use any modules or the split function?

    I can understand that in some companies you are not allowed to install any odd module on your system, but not using a built-in function? It is like saying: "please add this list of figures but don't use +!"

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

      No + or =

      sub add_em { my $sum; for (@_) { for (1..$_) { $sum--; } } return -$sum; } print add_em(1..5);

      Sorry just couldn't resist ;)


      ___________
      Eric Hodges
        No +, - or =:
        print sum(1..10); sub sum { return scalar map { 1..$_ } @_ }

        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Sorting The Date format Values without using any perl modules.
by johnnywang (Priest) on Dec 26, 2005 at 21:05 UTC
    no modules, and no split, why? anyhow:
    use strict; # use schwartzian transform if the size is big my @dates1 = ( '05-11-2006', '01-01-2005' , '04-12-2005' , '22-03-2005 +'); @dates1 = sort{substr($a,6,4)<=>substr($b,6,4)||substr($a,3,2) <=>subs +tr($b,3,2)||substr($a,0,2)<=>substr($b,0,2)}@dates1; print join("\n",@dates1); print "\n\n"; # this format is easy, it's just alpha-numeric my @dates2 = ( '2005-12-01' , '2005-11-02' , '2005-12-07'); my @dates2 = sort @dates2; print join("\n",@dates2); __OUTPUT__ 01-01-2005 22-03-2005 04-12-2005 05-11-2006 2005-11-02 2005-12-01 2005-12-07
Re: Sorting The Date format Values without using any perl modules.
by TedPride (Priest) on Dec 26, 2005 at 21:21 UTC
    Since your dates appear to be fixed-width, and are arranged year-month-day, there's no reason why you can't use the basic sort, as mentioned above:
    my @list = ('2005-12-01', '2005-11-02', '2005-12-07'); @list = sort @list; print join "\n", @list;
    If you want them from most recent to least recent, just reverse:
    @list = reverse sort @list;
    Things get a bit more difficult if your dates are arranged in a different order, but it's still fairly easy to do:
    use strict; use warnings; my @sort = ('05-11-2006', '01-01-2005', '04-12-2005', '22-03-2005'); @sort = map { join '-', reverse split /-/ } sort map { join '-', reverse split /-/ } @sort; print join "\n", @sort;
Re: Sorting The Date format Values without using any perl modules.
by fishbot_v2 (Chaplain) on Dec 26, 2005 at 22:52 UTC
    use strict; use warnings; my @list = ( '2005-12-01' , '2005-11-02' , '2005-12-07'); my @sorted = map { $_->[3] } sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] || $a->[2] <=> $b->[2] } map { [ unpack( 'A4 x[A] A2 x[A] A2', $_ ), $_ ] } @list;

    Your restrictions are beyond baffling.

Re: Sorting The Date format Values without using any perl modules.
by merlyn (Sage) on Dec 26, 2005 at 23:54 UTC
    I wanto sort @list. But without using any Date Sort modules. But we I can use perl's sort function.

    How that can be done.

    NOTE:

    Please don't use split also.

    I smell Homework. Arbitrary restrictions (no modules, no use of sort, wtf?)... the stumbled "we".

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Sorting The Date format Values without using any perl modules.
by blue_cowdawg (Prior) on Dec 27, 2005 at 03:49 UTC
        I wanto sort @list. But without using any Date Sort modules. But we I can use perl's sort function.
        Please don't use split also.

    WTF?

    Why the restrictions? What are you really trying to accomplish here?

    Looking at your posts you're not even consistant with the format of the dates in question...

    Read the doco for the sort function and take a look at the ability to define a function that sort will use to do its thing. Give that a try and come back to us and show us some code.

        "Keep pouring your ideas"

    Everybody has to believe something... I believe I'll pour another beer....


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: Sorting The Date format Values without using any perl modules.
by blazar (Canon) on Dec 27, 2005 at 14:30 UTC
    If your dates are precisely in that format, i.e. YYYY-MM-DD, then a plain (string-wise) sort should just do:
    $ perl -le 'print for sort qw/2005-12-01 2005-11-02 2005-12-07/' 2005-11-02 2005-12-01 2005-12-07
[OT] "please don't" [was: "Re: Sorting The Date format..."]
by blazar (Canon) on Dec 27, 2005 at 15:04 UTC
    I wanto sort @list. But without using any Date Sort modules. But we I can use perl's sort function.

    I find this mostly annoying. Every now and again someone pops up and asks "how can I do XYZ without using any module?" In most cases this is plainly stupid - check e.g. this quotation, and is being asked because the person who asks does not have root privileges and ignores that modules can be installed locally too. See for example this section of the Tutorials.

    In this case your post may suggest you're asking about homework instead, which is also advised against here. Personally I don't find anything wrong with it, provided that you clearly state so and you show what you've tried, so that we do not give ready-made solutions, which most of us won't do in any case -because we're not a helpdesk- and help you to learn instead.

    Please don't use split also.

    This also smells too much like homework, which I don't like. Indeed, if you have your numbers e.g. in a "MM-DD-YYYY" format as some of your post seem to imply, then it is quite natural to get individual chunks to sort upon like thus:

    my ($m, $d, $y) = split /-/;

    you don't like it? Then

    my ($m, $d, $y) = /\d+/g;

    will work just the same if you trust the format of your dates. Now, is this acceptable for your teacher?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://519147]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (13)
As of 2014-07-23 18:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (149 votes), past polls