Monday, October 25, 2010

Perl job interview questions (2)

Perl job interview questions (1)



10.  Using Perl to replace  bar by baz in fileA.

to replace first bar in fileA:
perl -pi -e 's/bar/baz/' fileA
to replace all bar:
perl -pi -e 's/baz/bar/g' fileA
(-p: assume loop like -n but print line also, like sed;
-e: one line of program
-i[extension]: edit <> files in place (makes backup if extension supplied)
perl -pi'.bak' -e 's/bar/baz/g' fileA
copy old fileA to fileA.bak, then replace all bar in fileA

11.  Assign 50 to scalar price  and output price and current time.

#!/usr/bin/perl
# by jiansen
$Price=50;
$day_of_year = (localtime(time()));
print <<EOF;
Today is $day_of_year.
The price is $Price.
EOF

12. Input two numbers  and output the sum.

#!/usr/bin/perl
print "Type in first number: ";
$x = <stdin>;
chop($x);
print "Type in second number: ";
$y =
<stdin>;
chop($y);
$z = $x + $y;
print "$x + $y = $z\n";


13. The same as question 12, add a choice "do it again" to repeat or stop.

#!/usr/bin/perl
$doagain = "yes";
while($doagain eq "yes") {
$x = &getnumber;
$y = &getnumber;
$z = $x + $y;
print "$x + $y = $z\n";
print "Do it again? (yes or no) ";
$doagain = <STDIN>;
chop($doagain);
}
  sub getnumber {
      print "Type in a number: ";
      $number = <STDIN>;
      chop($number);
      $number;
  }

14. Input a series of number, until ctrl D to stop and output the sum.

#!/usr/bin/perl
print " input a number (ctr D to stop)\n";
while (<>) {
print " input a number\n";
$total += $_;
}
print " The total is $total.\n";

15.  Search for a file in a directory and its sub-directories.  

#!/usr/bin/perl
# search for a file in all subdirectories
if ($#ARGV != 1) {
    print "usage: find_file filename directory\n";
    exit;
}
$filename = $ARGV[0];
# look in the directory
$dir = $ARGV[1];
&searchDirectory($dir);

sub searchDirectory {
    local($dir);
    local(@lines);
    local($line);
    local($file);
    local($subdir);

    $dir = $_[0];
    # check for permission
    if(-x $dir) {

        # search this directory
        @lines = `cd $dir; ls -l | grep $filename`;
        foreach $line (@lines) {
            $line =~ /\s+(\S+)$/;
            $file = $1;
            print "Found $file in $dir\n";
        }

        # search any sub directories
        @lines = `cd $dir; ls -l`;
        foreach $line (@lines) {
            if($line =~ /^d/) {
                $line =~ /\s+(\S+)$/;
                $subdir = $dir."/".$1;
                &searchDirectory($subdir);
            }
        }
    }
}

16.Difference between s/foo/bar/; s/foo/bar/g; s/foo/bar/gi; if(m/foo/)...


s/foo/bar/;
replaces the first occurrence of the exact character sequence foo with bar;

s/foo/bar/g;
replaces any occurrence of the exact character sequence foo;

s/foo/bar/gi;
replaces any occurrence of foo case-insensitively in the “current string”;

if(m/foo/)...
tests whether the current string contains the string foo.

17. Check user login status using system.


#!/usr/bin/perl
#checkuser.pl
# check user login status
#
if ($#ARGV != 0) {
    print "usage: checkuser.pl user\n";
    exit;
}

$user = $ARGV[0];

    $cmd = "last |grep $user";
    print $cmd."\n";
    if(system($cmd)) { print "$user does not exsit\n"; }


18.  Does Perl have reference type?
Yes. Perl can make a scalar or hash type reference by using backslash operator.
For example
$str = "here we go"; # a scalar variable
$strref = \$str; # a reference to a scalar

@array = (1..10); # an array
$arrayref = \@array; # a reference to an array
Note that the reference itself is a scalar.
19. How do I do &lt; fill-in-the-blank &gt; for each element in a hash?
#!/usr/bin/perl -w

%days = (
'Sun' =&gt;'Sunday',
'Mon' =&gt; 'Monday',
'Tue' =&gt; 'Tuesday',
'Wed' =&gt; 'Wednesday',
'Thu' =&gt; 'Thursday',
'Fri' =&gt; 'Friday',
'Sat' =&gt; 'Saturday' );

foreach $key (sort keys %days) {
print "The long name for $key is $days{$key}.\n";
}
 
 
20. Regular expressions in Perl.

Metacharacters

char meaning
^ beginning of string
$ end of string
. any character except newline
* match 0 or more times
+ match 1 or more times
? match 0 or 1 times; or: shortest match
| alternative
( ) grouping; “storing”
[ ] set of characters
{ } repetition modifier
\ quote or special

Repetition

a*zero or more a’s
a+one or more a’s
a?zero or one a’s (i.e., optional a)
a{m}exactly m a’s
a{m,}at least m a’s
a{m,n}at least m but at most n a’s
repetition? same as repetition but the shortest match is taken


 

Special notations with \


Single characters
\t tab
\n newline
\r return (CR)
\xhh character with hex. code hh
“Zero-width assertions”
\b “word” boundary
\B not a “word” boundary
Matching
\w matches any single character classified as a “word” character (alphanumeric or “_”)
\W matches any non-“word” character
\s matches any whitespace character (space, tab, newline)
\S matches any non-whitespace character
\d matches any digit character, equiv. to [0-9]
\D matches any non-digit character

Examples

expression matches...
abc abc (that exact character sequence, but anywhere in the string)
^abc abc at the beginning of the string
abc$ abc at the end of the string
a|b either of a and b
^abc|abc$ the string abc at the beginning or at the end of the string
ab{2,4}c an a followed by two, three or four b’s followed by a c
ab{2,}c an a followed by at least two b’s followed by a c
ab*c an a followed by any number (zero or more) of b’s followed by a c
ab+c an a followed by one or more b’s followed by a c
ab?c an a followed by an optional b followed by a c; that is, either abc or ac
a.c an a followed by any single character (not newline) followed by a c
a\.c a.c exactly
[abc] any one of a, b and c
[Aa]bc either of Abc and abc
[abc]+ any (nonempty) string of a’s, b’s and c’s (such as a, abba, acbabcacaa)
[^abc]+ any (nonempty) string which does not contain any of a, b and c (such as defg)
\d\d any two decimal digits, such as 42; same as \d{2}
\w+ a “word”: a nonempty sequence of alphanumeric characters and low lines (underscores), such as foo and 12bar8 and foo_1

No comments:

Post a Comment