Programming Fundamentals/Strings/Perl

From Wikiversity
Jump to navigation Jump to search

strings.pl[edit]

#!/usr/bin/perl

# This program splits a given comma-separated name into first and last name
# components and then displays the name.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Perl_Programming

sub get_name
{
    my $name;
    my $index;
    
    do
    {
        print("Enter name (last, first):\n");
        $name = <>;
        chomp($name);
        $index = index($name, ",")
    } while $index == -1;
    
    return $name;
}

sub get_last
{
    my ($name) = @_;
    my $last;
    my $index;

    $index = index($name, ",");
    if ($index == -1)
    {
        $last = "";
    }
    else
    {
        $last = substr $name, 0, $index;
    }
    
    return $last;
}

sub get_first
{
    my ($name) = @_;
    my $first;
    my $index;

    $index = index($name, ",");
    if($index == -1)
    {
        $first = "";
    }
    else
    {
        $first = substr $name, $index + 1;
        $first = ltrim($first);
    }

    return $first;
}

sub display_name
{
    my ($first, $last) = @_;
    
    print("Hello " . $first . " " . $last . "!\n");
}

sub ltrim
{
    my ($text) = @_;
    
    if ((substr $text, 0, 1) == " ")
    {
        $text = substr $text, 1
    }
    
    return $text;
}

sub main
{
    my $name;
    my $last;
    my $first;

    $name = get_name();
    $last = get_last($name);
    $first = get_first($name);
    display_name($first, $last);
}

main()

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own Perl compiler / interpreter / IDE.

See Also[edit]