• Welcome to Valhalla Legends Archive.
 

[Perl] String Functions

Started by Mr. Neo, January 15, 2005, 11:36 AM

Previous topic - Next topic

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.


#!/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;
}

Kp

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]);
}
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

Mr. Neo

I forgot all about substr.  Thanks for pointing out how to improve it even further.

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.



#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