in reply to Non-greedy substitution

And here the classical way to catch the last segment.

Reusing choroba's tests.

#!/usr/bin/perl use warnings; use strict; use experimental qw( signatures ); sub non_oxford_list($s) { $s =~ s/,([^,]+)$/ and$1/r } use Test::More tests => 3; is non_oxford_list('A'), 'A'; is non_oxford_list('A, B'), 'A and B'; is non_oxford_list('A, B, C'), 'A, B and C';

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^2: Non-greedy substitution
by LanX (Saint) on Nov 16, 2024 at 08:17 UTC
    > the classical way

    There are more than one way to go old-school

    use warnings; use strict; sub non_oxford_list { my ($s) = @_; my $p = rindex $s, ','; substr ($s,$p,1) = " and" if $p > -1; return $s; } use Test::More tests => 3; is non_oxford_list('A'), 'A'; is non_oxford_list('A, B'), 'A and B'; is non_oxford_list('A, B, C'), 'A, B and C';

    FWIW: rindex , substr

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery