Tuesday, February 16, 2010

Perl interview questions Part #5

1) How to open and read data files with Perl?

Answer:

#!/usr/local/bin/perl

print ("Word to search for: $ARGV[0]\n");
$filecount =1;
$totalwordcount = 0;

while($filecount <= @ARGV-1) { unless (open (INFILE, $ARGV[$filecount]\n"); die ("Can't open input file $ARGV[$filecount]\n"); } $wordcount =0; while($line=) {
chop($line);
@words = split(/ /, $line);
$w =1;
while ($w<=@words) {
if ($words[$w-1] eq $ARGV[0]) {
$wordcount +=1;
}
}
print ("occurrences in file $ARGV[$filecount]: ");
print ("$wordcount\n");
$filecount ++;
$totalwordcount +=$wordcount;
}
print ("total number of occurrences: $totalwordcount\n");


Command line:
$perl program ERROR log1 log2
Word to search for: ERROR
occurrences in file log1: 1
occurrences in file log2: 0
total number of occurrences: 1


2) How do I do fill_in_the_blank for each file in a directory?

Answer:

# print out a list of files in the current directory

#!/usr/perl -w
opendir(DIR, ".");
@file=readdir(DIR);
closedir(DIR);

foreach $file(@files) {print "$file\n");
}

Perl interview questions Part #4

1) What is the difference between for and foreach?

Answer:
There's no difference between them.

e.g.
# For loop example
for ($count=1; $count<=@words; $count++){
  if($words[$count-1] eq "the" ) {
      print ("found the word 'the'\n");
   }
}

# foreach loop example
foreach $word(@words) {
   if ($word eq "the" {
      print ("found the word 'the'\n");   }
}

#  while loop example
$count =1;
while ($count<=@words) {
if($words[$count-1] eq "the" ) {
      print ("found the word 'the'\n");
   }
  $count++;

}


2)  What is the difference between exec and system?

Answer:
exec runs the given process, switches to its name and never returns
e.g. exec(PROGRAM);

system folks the given process, wait for its to complete and then return.
e.g. $result = system(PROGRAM); 

3) What does this symbol mean '->'?

Answer:
In Perl, it is an infix dereference operator, for array or hash key, or a subroutine, then the ihs must be a reference. It can also used as method invocation.

The arrow operator also allows you to dereference references to arrays or hashes. The arrow operator makes more complex structures easier to read. The first example shows accessing an element of an array reference:

#!/usr/bin/perl
use strict;
use warnings;

my $array_ref = ['apple', 'banana', 'orange'];
print "My first fruit is: " . $array_ref->[0] . "\n";


This would produce the following output:
My first fruit is: apple


The next example shows accessing elements of an hash refernce:
#!/usr/bin/perl
use strict;
use warnings;

my $hash_ref = {name => 'Becky', age => 23};
foreach my $k (keys %$hash_ref) {
print "$k: " . $hash_ref->{$k} . "\n";
}

This produces the following output:
name: Becky


Subroutine references work the same way, using parenthesis:
#!/usr/bin/perl
use strict;
use warnings;

my %hash = (frogs => sub {print "Frogs\n"});
$hash{$frogs}->();
4) Perl regular exp are greedy. What is it mean by that?

Answer:
It tries to match the longest string possible.

5) What is the difference between C++ and Perl?

Answer:
1. Perl can have objects whose data cannot be accessed outside its class,
but C++ cannot do it.

2. Perl can use closures with unreachable private data as objects,
and C++ doesn't support closures.

e.g. my $print_hello = sub { print "Hello, world!"; }
$print_hello->();

3. C++ does support pointer arithmetic via 'int *ip=(int*)&object', allowing you do
look over the object. Perl doesn't support pointer arithmetic.

4. C++ supports '#define private public' to change the access right to foreign object. Perl doesn't support them.

Perl interview questions Part #3

1) What is the difference between die and exit?

Answer:
Die prints out stderr message in the terminal before exiting the program. Die also can evaluate expression before exiting.
Exit just terminates the program

2) Where do you go for perl help?

Answer: perldoc command with -f option is the best. 

3) What is scalar, array and hash in perl?

Answer:
Perl has 3 command data type:

$scalar is the basic variable. It could be letters, digits and underscore characters

$array is a collection of scalar.
e.g. @fruit = ("apple", "bananas", "orange");

foreach $goodfruit (@fruit) {
    if ($goodfruit eq "apple")
{
    print ("found $goodfruit in the list\n");
}
}

%hash: it is like an associative array. It is a collection of scalar data with individual elements selected by some index value which essentially are scalars and called as keys. Each key corresponds to some values.

e.g.

%fruit = ( "apple"=>17,
                "bananas"=>9,
                "oranges"=>"none");

foreach $holder (keys(%fruit))
{
     $numfruit = %fruit{$holder};
    print ("$holder = $numfruit \n");
}

4) What does 'qw()' mean? What is the use of it?

Answer:
qw is a construct which quotes word delimited by spaces.
e.g. @array = qw(1234);   # same as @array=("1","2","3","4");

5) What is the difference between Perl and shell script?

Answer:
Whatever you can do in the shell script, it can be done in Perl. However, Perl gives you an extened advantages of having enormous library. You don't need to write everything from scartch.

6) What is stderr() in Perl?

Answer:
A special file handler to standard error in any package.

7) What is a regular expression?

Answer:
It defines a pattern for a search to match.

Simple String Comparisons

The most basic string comparison is
$string =~ m/sought_text/;
The above returns true if string $string contains substring "sought_text", false otherwise.

If you want only those strings where the sought text appears at the very beginning, you could write the following:
$string =~ m/^sought_text/;

Similarly, the $ operator indicates "end of string". If you wanted to find out if the sought text was the very last text in the string, you could write this:
$string =~ m/sought_text$/;

Now, if you want the comparison to be true only if $string contains the sought text and nothing but the sought text, simply do this:
$string =~ m/^sought_text$/;

Now what if you want the comparison to be case insensitive? All you do is add the letter i after the ending delimiter:
$string =~ m/^sought_text$/i;

Using Simple "Wildcards" and "Repetitions"

Calling these "wildcards" may actually conflict with the theoretical grammar and syntax of Perl, but in fact is the most intuitive way to think of it, and will not lead to any coding mistakes.
.   Match any character
\w  Match "word" character (alphanumeric plus "_")
\W  Match non-word character
\s  Match whitespace character
\S  Match non-whitespace character
\d  Match digit character
\D  Match non-digit character
\t  Match tab
\n  Match newline
\r  Match return
\f  Match formfeed
\a  Match alarm (bell, beep, etc)
\e  Match escape
\021  Match octal char ( in this case 21 octal)
\xf0  Match hex char ( in this case f0 hexidecimal)

You can follow any character, wildcard, or series of characters and/or wildcard with a repetiton. Here's where you start getting some power:
*      Match 0 or more times
+      Match 1 or more times
?      Match 1 or 0 times
{n}    Match exactly n times
{n,}   Match at least n times
{n,m}  Match at least n but not more than m times
Now for some examples:
$string =~ m/\s*rem/i;   #true if the first printable text is rem or REM
$string =~ m/^\S{1,8}\.\S{0,3}/;   # check for DOS 8.3 filename 
                                   #  (note a few illegals can sneak thru
 
 
 

Perl interview questions Part #2

1) How to substitute a particular string in a file containing million of record?

perl -p -i bak -e 's/search_str/replace_str/g' filename

-p  Is name a named pipe?
-e  Evaluate replacement string as expression
-g change all occurances of the pattern
-i  ignore case in pattern

Or you can write the following code:

--replace.pl---

#!/usr/bin/perl

if(-e $ARGV[0])
{
    $cmd = 'copy $ARGV[0] $ARGV[0].bak';
    `$cmd`;
}
else
{
    print 'File does not exist.\n';
    exit;
}

open(INPUT,'$ARGV[0].bak') or die 'Cannot open file: $!\n';
open(OUTPUT,'>$ARGV[0]');

while(INPUT){
    $_ =~ s/$ARGV[1]/$ARGV[2]/g;
    print $_;
    print OUTPUT $_;
}

close INPUT;
close OUTPUT;


2) How to implement stack in Perl?

Answer: Use puch() and pop() function in the perl
              e.g.  @myNames = ('Larry', 'Curly');

                        push(@myNames, 'Moe'); # it push a value onto the end of the array.
                                                                 #  @myNames = ('Larry', 'Curly', 'Moe');

                        $oneName= pop(@myNames);    # it remove and return the last element of the array
                                                                            #  @myNames = ('Larry', 'Curly');
                                                                            # $oneName = 'Moe'

              shift() function is used to remove and return the first element from an array.
                        $oneName= shift(@myNames);    # it remove and return the first element of the array
                                                                            #  @myNames = ('Curly', 'Moe');
                                                                            # $oneName = 'Larry'

             unshift() function is used to add a value or values onto the beginning of an array.

                        @myNames = ('Curly', 'Moe');
                         unshift(@myNames, 'Larry'); # @myName =('Larry', 'Curly', 'Moe')

3) What is Grep used for in Perl?

Answer:
@LIST = grep(EXPRESSION, @ARRAY);
Perl's grep() function runs a regular expression on each element of an array, and returns only the elements that evaluate to true.

@myNames = ('Jacob', 'Michael', 'Joshua', 'Matthew', 'Alexander', 'Andrew');
@grepNames = grep(/^A/, @myNames);  # @grepNames becomes ('Alexander', 'Andrew').


4) Explain the difference between 'my' and 'local' variable scope declarations?

Answer:
    Both of them are used to declare local variables. The variables declared with 'my' can live only within the block and cannot gets it's visibility inherited functions called within that block. The "local" variables can live within the block and have its visibility in the functions called within the block.

5) What are the arguments w normally use for Perl interpreter?

Answer:
-e for execute
-c to compile
-d to call the debugger on the file specified
-T for traint mode for security/input checking
-W for show all warning mode
-w to show less warning
-strict pragma is used when you should declare variables before their use 

6) What is it meants by '$_' ?

Answer:

It is a default variable which holds automatically, a list of arguments passed to the subroutine within parentheses.

Monday, February 15, 2010

Perl interview questions Part #1

1) How do you know the reference of a variable whether it is a reference, scaller, hash or array?


Answer:    Perl provides the ref() function so that you can check the reference type before dereferencing a reference.


If the referenced object has been blessed into a package, then that package name is returned instead. You can think of ref() as a typeof() operator.

e.g.
if (ref($r) eq "HASH") {
print "r is a reference to a hash.\n";
}
if (!ref($r)) {
print "r is not a reference at all.\n";
}


2) What is the difference between "chop" and "chomp" function?
Answer:
"Chop" function removes the last character completely from the scaler.
"Chomp" function removes the last character if it is newline. By default, chomp 
use the current define $INPUT_RECORD_SEPARATOR $/( default value 'n' ).

3) Print this array @not_sort_list in reversed case-insensitive order
Answer:
@sort_list = sort {lc($a) cmp lc($b)} @not_sort_list;

lc function convert all character into lower case

4) What is '->' in Perl?
Answer:
It's a symbolic link to link one file name to a new name.
e.g. file1->file2, vi file1 ; you are really read the file2

5) How do you create a directory if not there?
Answer:
use strict;
my $path = "folder1/folder2/folder3";
# need to use forward slashes for perl, even under windows.
my $createdir="mkdir -p $path";
# does mkdir -p work under windows???
if (-d $path)
  {
print "$path exists\n" }
else
  { print "mkdir failed\n" unless
system($createdir) }

Perl Script basic

Perl is know as interpretive languages. It does not require more complicated processing. C++ or C are compiled language.

String and numeric comparison operators

String Operator Comparison Equivalent numeric operator
lt Less Then <
gt Greater than >
eq Equal to ==
le Less than or equal to <=
ge Greater than or equal to >=
ne Not equal to !=
cmp Compare , returning 1 (greater then),
0
(equal) , -1 ( less than)
<=>


Single-Quoted strings vs Double-Quoted String:
1) double-quoted strings is that scalar variables are replaced by their values in double-quoted strings but not in single quoted string.

  e.g.
  $string = " a string";
  $text = " This is $string";    # become " This is a string"

   $text = 'This is $string';   # remains 'This is $string'


2) The\ character has not special meanings in single-quoted strings:

    e.g.
    $text ='This is a string.\n' # remains This is a string. \n


Conditional Operator:

$result =$var ==0 ? 14: 7;

is identical to the following:

if($var==0) {
         $result = 14;
} else{
        $result = 7;
}

Examples of assignment operators:

$a +=1;   #   $a= $a +1;
$a %= 2;   # $a = $a%2 ; reminder and assignment
$a ^=2;  # $a =$a ^2; bitwise XOR and assignment
++$a ;  # autoincrement, pre-increment operation, add 1 before doing anything
$a++;   # post-increment operation

Wednesday, February 3, 2010

PLL related

What's PLL?

A phase-locked loop (PLL) is an electronic circuit with a voltage- or current-driven oscillator that is constantly adjusted to match in phase (and thus locked on) the frequency of an input signal. PLLs are used for frequency control. They can be configured as frequency multipliers, dividers, demodulators, tracking generators or clock recovery circuits.




What does this do? The crystal generates a frequency of 10 MHz in our example. This frequency gets fed to the PD. The VCO output is zero right now so the PD output is high because the frequencies differ a lot. The PD output gets fed into the VCO and generates a frequency. This goes back to the PD and so on - eventually the VCO will lock onto the frequency of the crystal. And the output of the VCO will be 10 MHz. This is a basic PLL circuit.
Now you ask where's the flexibility? What we have right now is equivalent to a crystal oscillator!

Let's see.. We want an output of 20 Mhz for this example. What we do now is add a divide-by-two counter between the VCO output and the PD. This 'tricks' the PD into thinking our output frequency is only the half of what it really is- so it starts regulating the voltage to the VCO. Voila 20 MHz. If we used a programmable divider here we could change frequencies on the fly.



Now we can multiply frequencies by integer values. But how can we multiply our frequency by fractional values or divide it?
For example we want 10 Mhz x 3.5 for an output of 35 Mhz. This is done by adding another pre-divider [whats the correct term here?] between the crystal and the PD. In our example we could use a pre-divider of 2 and a divider of 7. Our output would be 10 Mhz / 2 * 7 = 35 MHz.

This is our PLL in all its goodness:




The added loop filter is not required for general understanding. It's here for completeness. The loop filter is designed to match the characteristics required by the application of the PLL. For example, it determines how fast the signal frequency can change and still maintain lock. This is the maximum slewing rate. The narrower the loop filter bandwidth the smaller the achievable phase error. This comes at the expense of slower response and reduced capture range.

Search This Blog