rakheek has asked for the wisdom of the Perl Monks concerning the following question:

Monks and wonderful friends, I am trying to split the date by '/'. I tried the code. It does not work. Please help. Regards, Rakhee
@date_array = split(/\//, $date); $new_date = join('-', @date_array[2], @date_array[1], @date_ar +ray[0]); return $new_date;

Replies are listed 'Best First'.
Re: How do I split by '/'
by johngg (Canon) on Mar 16, 2010 at 18:35 UTC

    Not the cause of your problem but choosing a different regex delimiter can improve readability when split'ing or some other match operation on a slash. This is particularly true when matching *nix paths, e.g.

    if ( $path =~ /\/usr\/local\/bin\// ) { ... }

    is much harder to follow than

    if ( $path =~ m{/usr/local/bin/} ) { ... }

    I hope this is of interest.

    Cheers,

    JohnGG

Re: How do I split by '/'
by kennethk (Abbot) on Mar 16, 2010 at 18:11 UTC
    Assuming you have appropriate input, the code you've posted will function. warnings suggests you should be typing $date_array[2] in place of @date_array[2] (the latter is actually a slice instead of a scalar element), but this should not affect your result. Are you sure you are feeding it what you think you are? The following works as I would expect:

    #!/usr/bin/perl use strict; use warnings; my $date = '1/2/03'; my @date_array = split(/\//, $date); my $new_date = join('-', $date_array[2], $date_array[1], $date_array[0 +]); print $new_date;
Re: How do I split by '/'
by toolic (Bishop) on Mar 16, 2010 at 19:21 UTC
    Yet another way...
    use strict; use warnings; my $date = '03/16/2010'; my $new_date = join '-', reverse split m{/}, $date; return $new_date;
    You might also want to consider using one of the many CPAN Date modules.
Re: How do I split by '/'
by ssandv (Hermit) on Mar 16, 2010 at 19:00 UTC

    Oddly enough, you could have typed

    split '/',$date;
    to split on '/'. You don't have to use regex delimiters for the expression to split on, and it often helps with readability not to.

Re: How do I split by '/'
by umasuresh (Hermit) on Mar 16, 2010 at 18:27 UTC
    Is this what you tried?
    $date = '03/16/2010'; @date_array = split(/\//, $date); $new_date = join('-', @date_array[2], @date_array[1], @date_array[0]); print $new_date;
    This worked for me: 2010-16-03
Re: How do I split by '/'
by AnomalousMonk (Archbishop) on Mar 17, 2010 at 07:26 UTC

    And if you really want to use a slice:

    >perl -wMstrict -le "my $date = '2010/03/17'; print qq{'$date'}; my @date_array = split '/', $date; my $new_date = join '-', @date_array[2, 1, 0]; print qq{'$new_date'}; " '2010/03/17' '17-03-2010'