Valhalla Legends Forums Archive | General Programming | [Perl] String Functions

AuthorMessageTime
Mr. Neo
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.

[code]
#!/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;
}
[/code]
January 15, 2005, 5:36 PM
Kp
Yours is a waste of effort.  Try this:

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

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

sub mid {
    return substr($_[0], $_[1], $_[2]);
}[/code]
January 15, 2005, 7:18 PM
Mr. Neo
I forgot all about substr.  Thanks for pointing out how to improve it even further.
January 15, 2005, 7:55 PM
Adron
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.


[code]
#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

[/code]




January 16, 2005, 11:38 PM

Search