Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

rearranging a string.new

by drock (Beadle)
on Nov 21, 2005 at 19:14 UTC ( #510526=perlquestion: print w/replies, xml ) Need Help??

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

In my situation I have a string like so:
my $string = '20050516';
and I want to rearrange it to look like: 05162005, so I tried:
my $newstring = substr($string,0,8).substr($string,0,4).substr($string +,8,0);
But my problem is: it's leaving 2005 in the beginning of the string to look like 200505162005 when all I need is 05162005 thx derek

Replies are listed 'Best First'.
Re: rearranging a string.new
by ikegami (Patriarch) on Nov 21, 2005 at 19:19 UTC
    Your arguments were completely wrong. Maybe you should reread the documentation for substr. Corrected:
    my $newstring = substr($string, 4, 2) # Month (was at 4 len 2) . substr($string, 6, 2) # Day (was at 6 len 2) . substr($string, 0, 4); # Year (was at 0 len 4)
    which can be simplified to
    my $newstring = substr($string, 4, 4) # M+D (was at 4 len 4) . substr($string, 0, 4); # Year (was at 0 len 4)
Re: rearranging a string.new
by VSarkiss (Monsignor) on Nov 21, 2005 at 20:48 UTC
Re: rearranging a string.new
by davidrw (Prior) on Nov 21, 2005 at 19:25 UTC
    Can also use a regex or substitution...
    my $string = '20050516'; my $newstring; $newstring = $2 . $1 if $string =~ /(\d{4})(\d{4})/; warn $newstring; (my $newstring = $string) =~ s/(\d{4})(\d{4})/$2$1/; warn $newstring;
    Could also use a more robust regex if desired (trivial example is /(200[012345])(\d{4})/) and depending on context.
Re: rearranging a string.new
by Corion (Patriarch) on Nov 21, 2005 at 19:20 UTC

    It's not "leaving the 2005 in front". Check your code, for example by running the below code:

    my $string = '20050516'; my $newstring = substr($string,0,8). "!" . substr($string,0,4) . "!" . + substr($string,8,0); print $newstring;

    If you look at the output of this snippet, you will see where your errors lie.

Re: rearranging a string.new
by ptum (Priest) on Nov 21, 2005 at 19:20 UTC
    You may want something more like:
    my $newstring = substr($string,4,2) . substr($string,6,2) . substr($st +ring,0,4);
    No good deed ever goes unpunished. -- (attributed to) Oscar Wilde

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2023-02-06 12:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (34 votes). Check out past polls.

    Notices?