walkingthecow has asked for the wisdom of the Perl Monks concerning the following question:
I have a scalar variable, and below are some examples of the values that may be in the variable:
1,2,3,4
8,9,10,11
7,8,9,10
12,13,14,15
Basically, what I'd like to do is to put a zero before any single digit (i.e., 9 becomes 09, 8 becomes 08, 10 stays 10, and so on). So, I know I can do this by splitting the scalar into an array, then go through each value of the array and say if ($value =~ /(\d)/) then make it 0$1, and then put it all back together. However, I am wondering if there is any way I can do it without splitting the scalar. For example, 8,9,10,11 becomes 08,09,10,11. I have the following code, but it only works in situations where they are all single digits (e.g., 1,2,3,4):
1,2,3,4
8,9,10,11
7,8,9,10
12,13,14,15
Basically, what I'd like to do is to put a zero before any single digit (i.e., 9 becomes 09, 8 becomes 08, 10 stays 10, and so on). So, I know I can do this by splitting the scalar into an array, then go through each value of the array and say if ($value =~ /(\d)/) then make it 0$1, and then put it all back together. However, I am wondering if there is any way I can do it without splitting the scalar. For example, 8,9,10,11 becomes 08,09,10,11. I have the following code, but it only works in situations where they are all single digits (e.g., 1,2,3,4):
if ( $channels =~ /(\d,)(\d,)(\d,)(\d)/ ) { $channels = "0${1}0${2}0${3}0$4"; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Replacing matches within string without splitting.
by Athanasius (Archbishop) on Jan 02, 2013 at 06:44 UTC | |
by walkingthecow (Friar) on Jan 02, 2013 at 07:26 UTC | |
Re: Replacing matches within string without splitting.
by BrowserUk (Patriarch) on Jan 02, 2013 at 06:44 UTC | |
Re: Replacing matches within string without splitting.
by NetWallah (Canon) on Jan 02, 2013 at 06:44 UTC | |
Re: Replacing matches within string without splitting.
by 2teez (Vicar) on Jan 02, 2013 at 06:39 UTC | |
Re: Replacing matches within string without splitting.
by johngg (Canon) on Jan 02, 2013 at 09:56 UTC | |
Re: Replacing matches within string without splitting.
by Anonymous Monk on Jan 02, 2013 at 08:29 UTC | |
Re: Replacing matches within string without splitting.
by AnomalousMonk (Archbishop) on Jan 02, 2013 at 18:37 UTC |
Back to
Seekers of Perl Wisdom