$string = join('-',unpack('A4 A4',pack('A*',$string)));
There must be a simpler way. Please share with me what it is, as I am unable to figure it out.
Thanks in advance.
Do you want to insert a hyphen in the middle of the string?
substr($string, (length $string)/2, 0) = '-';
... or insert a hyphen after the fourth character?
substr($string, 4, 0) = '-';
... or insert a hyphen after every fourth character, but not at the end?
$string =~ s/(.{4})(?=.)/$1-/g;
... or something else?
print "Just another Perl ${\(trickster and hacker)},"
The Sidhekin proves Sidhe did it!
You could simplify your own snippet somewhat:
$string = join '-', unpack 'A4 A*', $string;$string=~s/(....)/$1-/s;
$string =~ s/DF/D-F/g;or more generic
$string =~ s/^(.{4})/$1\-/g;
$string = sprintf("%4s-%4s", $string);
or this:
$string = join('-', (split($string))[0..4], (split($string))[0..4]);
my $string = "ABCDEFGH"; my @string = split //, $string; $final = (join "", @string[0..3])."-".(join "", @string[4..7]); print $final; # if my code is right, this is "ABCD-EFGH"
If you're going to do that you might as well do
#!/usr/bin/perl
@list = split //, 'ABCDEFGH';
s&&local$/;
&e&&y&;
&&d;& s#zoTfFdDsOt##g;
while/(\D)(\d+)/gi;
sub z{(&O-&O)*((&O-&O)*(&O-&O))}
sub o{&z-((&O-&O)*(&O-&O))+&O-&O}
sub T{&z-(&O-&O)}
sub f{&T+(&O-&O)}
sub F{(&O-(&O-&O))/(&O-&O)}
sub d{print chr shift}
sub D(@){map chr,@_}
sub s{print D$1->(@list[split//,$2])}
sub O{ord shift}
sub t{&z+&O-&O(A)}
__DATA__
#t50703010o507040703002o507040703004o507040703003F01020f5070
306057t50703050t50703060o507040703003T50703010T50703040o5070
40703005F01020t50703070T50703040o507040703005t50703030F01020
T50703010f5070306057T50703060t50703020T50703040o507040703005
Proves the same point!
my $string = "ABCDEFGH";
$string = sprintf("%.4s-%s", $string,substr($string,4,4));
Awkward, maybe, but I have tried it and it works.
#!/usr/bin/perl -w
use strict;
my $string = "ABCDEFGH";
print $string."<= before\n\n";
my $regexp = '\w{'.int(length($string)/2).'}';
$string =~ s/($regexp)/$1-/;
print $string."<= after\n\n";
exit;
ABCDEFGH<= before ABCD-EFGH<= after
perlmonks.org content © perlmonks.org and ambrus, Anonymous Monk, blyman, Clownburner, injunjoel, melora, Not_a_Number, Roy Johnson, Sidhekin
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03