Search code examples
perlsubstr

How to replace the last string character with a new string in Perl


I am iterating an excel sheet in one column B. If a cell contains a ", then replace it with Inches. However, when using the substr function, $newval remains blank. In the test run both $cell and $ind contain the right values. I got no errors and no warnings.

Why is $newval blank? I found this substr-example online and can't seem to figure out what I am doing differently:

An alternative to using substr as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice.

    my $s = "The black cat climbed the green tree";
    my $z = substr $s, 14, 7, "jumped from";    # climbed
    # $s is now "The black cat jumped from the green tree"

Here is my code:

    ...

    if($sheet->Range("B". $i)->{Value} =~ m/\"/)
    {
                    my $cell = $sheet->Range("B". $i)->{Value};
                    print $cell . "\n"; # Notebook 24"
                    my $ind = index($cell, '\"');
                    print $ind ."\n";   # -1                        
                    my $newval = substr($cell, $ind, 0, " Inches");
                    print $newval . "\n"; # (blank)
                    <STDIN>;
                    $sheet->Range("B". $i)->{Value} = $newval;                      
    }

    ...

EDIT: (ADDED AN EXAMPLE OUTPUT IN THE CONSOLE) enter image description here

EDIT 2: (INDEX IS NOW POSITIVE AND CORRECT)

...

if($sheet->Range("B". $i)->{Value} =~ m/\"/)
{
                my $cell = $sheet->Range("B". $i)->{Value};
                print $cell . "\n"; # Notebook 24"
                my $ind = index($cell, '"');
                print $ind ."\n";  # 11                       
                my $newval = substr($cell, $ind, 0, " Inches");
                print $newval . "\n"; # (blank)
                <STDIN>;
                $sheet->Range("B". $i)->{Value} = $newval;                       
}

...

CONSOLE OUTPUT:

enter image description here


Solution

  • Double quotes don't need a backslash in single quotes.

    index($cell, '\"');
    

    On the contrary: it searches for a backslash followed by double quotes, which isn't present in the string, so the returned value is -1.

    say index 'Notebook 24"', '\"';  # -1
    say index 'Notebook 24"', '"';   # 11