+1  A: 

if the directory you want to find is known beforehand.

$str = "blah blah cd /a/b/c blah";
if ( $str =~ /cd \/a\/b\/c/ ){
  print "found\n";
  chdir("/a/b/c");
}
ghostdog74
I was thinking about something like this:$str = "cd /a/b/c";@dir = split /\s/ , $str;$dir[1] = "chdir";$new_dir = join ($" , @dir );eval $new_dir;SO, why can't I cd/eval/exec the $new_dir command and go there?
T. Gruhn
+3  A: 
#!/usr/bin/perl

use strict; use warnings;

while ( my $line = <DATA> ) {
    if ( my ($path) = $line =~ m{^cd \s+ (/? (\w+) (?:/\w+)* )}x ) {
        warn "Path is $path\n";
        chdir $path
            or warn "Cannot chdir to '$path': $!";
    }
}

__DATA__
cd a
cd /a/b/c
cd /a

Output:

Path is a
Cannot chdir to 'a': No such file or directory at C:\Temp\k.pl line 8,  line 1.
Path is /a/b/c
Cannot chdir to '/a/b/c': No such file or directory at C:\Temp\k.pl line 8,  line 2.
Path is /a
Cannot chdir to '/a': No such file or directory at C:\Temp\k.pl line 8,  line 3.
Sinan Ünür
+2  A: 

What you really want is a dispatch table. When you encounter a command, like cd, you look up an associated subroutine in the dispatch table where you map valid commands to the code that you want to run:

%dispatch = (
     cd => sub { chdir( $_[0] ) }, 
     ...
     );

while( <> )
     {
     my( $command, @args ) = split;
     if( exists $dispatch{ $command } )
          {
          $dispatch{ $command }->(@args);
          }
     }

I have several extended examples of this sort of thing in Mastering Perl. The nice bit about this is that you don't change the processing loop when you have new commands, and you only handle the commands you intend to handle. Furthermore, you can construct that dispatch table directly from configuration.

brian d foy

related questions