ITNW 2310 - PERL
Allan Kochis,Adjunct Professor - CIT

Strings

  1. length
    PerlOutput
    #!/usr/bin/perl -w
    #
    #
    while(<>) {
       chomp;
       $a=$_;
       $long=length($a);
       print $long." bytes = ".$a."\n";
    }
    

    $ ./pl9a1.pl
    hello
    5 bytes = hello
    hello there
    11 bytes = hello there
    hello
    10 bytes = hello
    the rain in Spain
    17 bytes = the rain in Spain
    

  2. index
    PerlOutput
    #!/usr/bin/perl -w
    
    $string="To be or not to be that is the question.";
    
    $at=index($string,"the");
    
    print qq/"the" Found at byte $at \n/;
    
    $start=0;
    do {
        $at=index($string,"be",$start);
        if($at ne -1 ) {
            print qq/"be" Found at byte $at \n/;
            $start=$at+1;
        }
    } while($at != -1);
    

    "the" Found at byte 27
    "be" Found at byte 3
    "be" Found at byte 16
    

  3. rindex
    PerlOutput
    #!/usr/bin/perl -w
    
    $string="To be or not to be that is the question.";
    
    $at=rindex($string,"the");
    
    print qq/"the" Found at byte $at \n/;
    
    $start=length($string)-1;
    do {
        $at=rindex($string,"be",$start);
        if($at ne -1 ) {
            print qq/"be" Found at byte $at \n/;
            $start=$at-1;
        }
    } while($at != -1);
    

    "the" Found at byte 27
    "be" Found at byte 16
    "be" Found at byte 3
    

  4. substr
    PerlOutput
    #!/usr/bin/perl -w
    #
    #
    #
    $string="ACC UNIX Class";
    #       +01234567890123  left to right
    #        32109876543210  right to left
    
    print "String\t".$string."\n";
    
    print "String 0,1\t".substr($string,0,1)."\n";
    print "String 4,10\t".substr($string,4,10)."\n";
    print "String 4\t".substr($string,4)."\n";
    
    print "String -5\t".substr($string,-5)."\n";
    print "String -5,2\t".substr($string,-5,2)."\n";
    
    #
    # now use substr as lvalue
    #
    substr($string,4,4)="Perl";
    print "String replace\t".$string."\n";
    
    #
    # use substr as lvalue and limit changes
    #
    substr($string,0,3) =~ tr/A-Z/a-z/;
    print "String with tr\t".$string."\n";
    

    String	ACC UNIX Class
    String 0,1	A
    String 4,10	UNIX Class
    String 4	UNIX Class
    String -5	Class
    String -5,2	Cl
    String replace	ACC Perl Class
    String with tr	acc Perl Class
    

  5. tr
    PerlOutput
    #!/usr/bin/perl -w
    
    $string="To be or not to be that is the question.";
    
    $string=~ tr/ /:/;
    
    print $string."\n";
    
    $string=~ y/:/ /;
    
    print $string."\n";
    

    To:be:or:not:to:be:that:is:the:question.
    To be or not to be that is the question.
    

© Allan Kochis Last revision 10/19/2005