in reply to How do I use Split

Converting yyyy-mm-dd to dd-mm-yyyy format, also using a regex:

sub changedate { join '-', reverse shift =~ /\d+/g }

Replies are listed 'Best First'.
Re: (dkubb) Re: (2) Split
by sierrathedog04 (Hermit) on Feb 14, 2001 at 15:30 UTC
    I ran this and it works, but I am not sure I understand why.
    1. 'd+' is one or more digits. The 'g' option causes the regex to find all greedy matches of d+, which is, say, '2001', '02' and '14'.
    2. The regex returns a list of these finds.
    3. 'shift =~' causes the regex to read as input the first parameter sent to the changedate function.
    4. join and reverse are as usual.
    5. Finally, even though there is no explicit return in the sub, it by default returns the last value calculated, which is the the value returned by join.
    Wow! Is Perl powerful or what? I am in awe of Larry and the Perl 5 Porters who wrote it.
      I promise this will be the last "clarification" I make in this thread.

      You are close. You are very close. I would make these notes

      1. The 'g' option causes a global match - ie, find them all
      2. The regex, in this case, returns the list of all matches. In other cases, it will return how many matches were found. The difference is the context in which it is used. Since reverse() expects a list, it forces the regex to be evaluated in list context and, hence, returns the list.
      In a clarifying mood,
      mikfire