Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

text formatting ?

Status
Not open for further replies.

loosecannon1

Programmer
Feb 19, 2002
55
US
Hi All -

I need to insert a dash before the third to the last character of several strings.

For example:

Currently --> @array1 = qw(A-12001 A-1001 A-321001);

I Need --> @array2 = qw(A-12-001 A-1-001 A-321-001);

Any suggestions are appreciated.
 
This works:

@array1 = qw(A-12001 A-1001 A-321001);

foreach $element (@array1) {

$element=~s/(.+)(.{3})/$1-$2/ig;
push(@array2, $element);
}

foreach $one (@array2) {
print "$one\n";
}

Shagy
 
Actually, if you want to leave @array1 intact and not change the values, you need to do this:

@array1 = qw(A-12001 A-1001 A-321001);

foreach $element (@array1) {

$element=~/(.+)(.{3})/;
$new_element="$1-$2";
push(@array2, $new_element);
}

foreach $one (@array2) {
print "$one\n";
}
 
Another possibility
Code:
my @array2 = map { substr $_, -3, 0, '-'; $_ } @array1;

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top