Valhalla Legends Archive

Programming => General Programming => Topic started by: Mr. Neo on January 15, 2005, 11:36 AM

Title: [Perl] String Functions
Post by: Mr. Neo on January 15, 2005, 11:36 AM
It has annoyed me for sometime that Perl is missing four basic string functions; left, right, mid, trim.  I took a few minutes and created my own functions to mimic what these four do.  These functions follow the same format as the ones found in REALbasic, and probably Visual Basic.


#!/usr/bin/perl

sub left {
# Returns the first N characters in a source string
# $result = left("Hello World", 5) Returns Hello
my $source = shift;
my $count = shift;

if ($source =~ m/^(.{$count})/gi) {
return $1;
}
}

sub right {
# Returns the last N characters in a source string
# $result = right("Hello World",5) Returns World
my $source = shift;
my $count = shift;

if ($source =~ m/(.{$count})$/gi) {
return $1;
}
}

sub mid {
# Returns a portion of a string
# $result = mid("This is a test",10,4) Returns test
# First character is 0
my $source = shift;
my $start = shift;
my $len = shift;

$source =~ s/.{$start}//i;
if ($source =~ m/^(.{$len})/gi) {
return $1;
}
}

sub trim {
# Returns a string with trailing and following spaces removed
# $result = trim("  Hello World  ") Returns Hello World
my $source = shift;

$source =~ s/^\s+//;
$source =~ s/\s+$//;
return $source;
}
Title: Re: [Perl] String Functions
Post by: Kp on January 15, 2005, 01:18 PM
Yours is a waste of effort.  Try this:

sub left {
    return substr($_[0], 0, $_[1]);
}

sub right {
    return substr($_[0], $_[1]);
}

sub mid {
    return substr($_[0], $_[1], $_[2]);
}
Title: Re: [Perl] String Functions
Post by: Mr. Neo on January 15, 2005, 01:55 PM
I forgot all about substr.  Thanks for pointing out how to improve it even further.
Title: Re: [Perl] String Functions
Post by: Adron on January 16, 2005, 05:38 PM
I'll take this time to advise against using those functions. Use substr directly since the other alternatives are just calls to it with different arguments. When you come to a different language you should embrace it, not try to make it look like what you're used to. You're really just making things more complicated.



#define begin {
#define end }
#define program int
#define main main(int ac, char **av)
#define writeln(s) printf(s "\n")


program main
begin
  writeln("Hello World!");
end