Perhaps this will do the job?
use strict; use warnings; my $val1 = 5234; my @digits = split(//,$val1); my $string = join ('_',@digits); $string =~ s/_(\d)$/$1/ if @digits == 4; print $string, "\n"; #prints 5_2_34 # #$val1 5234 prints 5_2_34 #$val1 52 prints 5_2 #$val1 523 prints 5_2_3
Updated: Re question from OP

I am just trying to demonstrate a technique. Once you see how this works, you can adapt it for your exact specific needs. Like maybe if @digits is >4, that is an error or whatever. A subroutine would be like this (shamelessly plugging my code into toolic's loop structure, thanks toolic!): (this is 2nd update)

for (qw(5234 523 52)) { print append($_ , '_'), "\n"; } sub append { my ($val, $character) = @_; my @digits = split(//,$val); my $string = join ($character,@digits); $string =~ s/$character(\d)$/$1/ if @digits >= 4; return $string; }

In reply to Re: Check substitute digit by Marshall
in thread Check substitute digit by tart

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.