Wednesday, February 17, 2010

Previous Interview Questions

1) Try to model Stack in Verilog code?

module Stack (DataIO, Reset, Push, Pop, SP, Full, Empty, Err);
//Verilog code for stack

/* declare input, output and inout ports */
inout [3:0] DataIO;
input Push,Pop,Reset;
output Empty,Err;
Full,output [2:0] SP; // Stack pointer

// declare registers
regEmpty,Err;
Full,reg [2:0] SP;
reg [3:0] Stack[7:0];
reg [3:0] DataR;

/* continuous assignment of DataIO to DataR register, with delay 0 */
wire [3:0] #(0) DataIO = DataR;

// put DataR in high impedance, so the stack can get data

always @ (negedge Pop)
begin
DataR = 4'bzzzz;
end


always @ (posedge Push or posedge Pop or posedge Reset)
begin


   if (Reset==1)
   begin
     DataR = 4'bzzzz;
     SP = 3'b0;
     Full = 0;
     Empty = 0;
     Err = 0;
  end
 
    if (Push==1) begin
      //when the stack is empty
      if (Empty==1)
      begin
         Stack[SP] = DataIO;
         Empty = 0;
         if (Err==1)
         Err=0;
      end
     else // when the stack is full
     if(full==1)
     begin
        Stack[SP] = DataIO;
        Err = 1;
     end
     else
     begin
        SP = SP +1;
        Stack [SP] = DataIO;
        if (SP == 3'b111)
            Full = 1;
     end
end  // end of push


    if(Pop==1) begin
    /* if SP indicates the last location but the stack is not empty */
     if ((SP == 3'b000) && (Empty!=1)
     begin
        DataR = Stack[SP];
        Empty = 1;
     end
     else // if the stack is emtpy
       if(Empty==1)
       begin
        DataR = Stack[SP];
        Err = 1;
       end
     else
     begin
     DataR = Stack[SP];
     if (SP != 3'b000)
        SP = SP-1;
      // if the stack is full
     if (Err==1) Err = 0;
     if (Full==1) Full = 0;
    end
 end  // end of pop
end  // end of always loop

endmodule

2) what is difference between CAM and TCAM?

First, CAM stands for Content Addressable Memory. A CAM is a special type of memory; some would say the opposite of RAM. With normal computer memory (RAM) the operating system provides an address, and receives the data stored at the supplied address. With a CAM, the operating system supplies the data, and the CAM returns a list of addresses where the data is stored, if it finds any. Furthermore, a CAM searches the entire memory in one operation, so it is considerably faster than RAM.

The most commonly implemented CAMs are called binary CAMs. They search only for ones and zeros; a simple operation. MAC address tables in switches commonly get stored inside binary CAMs. With CAMs, the operating system can find what it needs in a single operation. In this case it's the switchport that data should be sent out, based on the given MAC address,

The TCAM is a Ternary CAM. This allows the operating system to match a third state, "X." The X state is a "mask," meaning its value can be anything. This lends itself well to networking, since netmasks (define) operate this way. To calculate a subnet address we mask the bits we don't care about, and then apply the logical AND operation to the rest. Routers can store their entire routing table in these TCAMs, allowing for very quick lookups.

3) One-hot state machine vs highly encoded state machine

Answer:

     One-hot state machine: better performance, easy encode
     highly encode state machine has less bit for state parameters
 
   e.g.

  Using Single Always For Sequential, Combo And Output Logic
//==================================================== 2 // This is FSM demo program using single always 3 // for both seq and combo logic 4 // Design Name : fsm_using_single_always 5 // File Name : fsm_using_single_always.v 6 //===================================================== 7 module fsm_using_single_always (
8 clock , // clock 9 reset , // Active high, syn reset 10 req_0 , // Request 0 11 req_1 , // Request 1 12 gnt_0 , // Grant 0 13 gnt_1
14 );
15 //=============Input Ports============================= 16 input clock,reset,req_0,req_1;
17 //=============Output Ports=========================== 18 output gnt_0,gnt_1;
19 //=============Input ports Data Type=================== 20 wire clock,reset,req_0,req_1;
21 //=============Output Ports Data Type================== 22 reg gnt_0,gnt_1;
23 //=============Internal Constants====================== 24 parameter SIZE = 3 ;
25 parameter IDLE = 3'b001,GNT0 = 3'b010,GNT1 = 3'b100 ;
26 //=============Internal Variables====================== 27 reg [SIZE-1:0] state ;// Seq part of the FSM 28 reg [SIZE-1:0] next_state ;// combo part of FSM 29 //==========Code startes Here========================== 30 always @ (posedge clock)
31 begin : FSM
32 if (reset == 1'b1) begin
33 state <= #1 IDLE;
34 gnt_0 <= 0;
35 gnt_1 <= 0;
36 end else
37 case(state)
38 IDLE : if (req_0 == 1'b1) begin
39 state <= #1 GNT0;
40 gnt_0 <= 1;
41 end else if (req_1 == 1'b1) begin
42 gnt_1 <= 1;
43 state <= #1 GNT1;
44 end else begin
45 state <= #1 IDLE;
46 end
47 GNT0 : if (req_0 == 1'b1) begin
48 state <= #1 GNT0;
49 end else begin
50 gnt_0 <= 0;
51 state <= #1 IDLE;
52 end
53 GNT1 : if (req_1 == 1'b1) begin
54 state <= #1 GNT1;
55 end else begin
56 gnt_1 <= 0;
57 state <= #1 IDLE;
58 end
59 default : state <= #1 IDLE;
60 endcase
61 end
62
63 endmodule // End of Module arbiter


4) Write a perl script to read a file and then count the "ERROR=number" ? Check the number did increase.

Answer:
    First, you can use grep -f patternfile source > target to generate a new log file with ERROR=# format or directly use perl to do it.


  Assume the log file has the format  "ERROR=number" format in some lines,

   #!/usr/bin/perl
   system(grep "ERROR" logfile > error_logfile);
 
   open(IN, "error_logfile") or die "Cannot open the error_logfile!";

    while($line=) {
   chop($line);
   @err_array = split(/\d/,$line);
   $w=1;
      while ($$w<= @err_array) {
         if($err_array[$w-1] < $err_array[$w])
           {           $err_incr_cnt +=1;
           }
        else
             {         $err_decr_cnt +=1;       
             }
        $w++; 
     }  
}
   print "Total number of error = $w";
   print "Error Increment counter = $err_incr_cnt";
   print "Error Decrement counter =$err_decr_cnt;

Perl Hash examples

Example:

    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    %name = ('Tom',26,'Peter',51,'Jones', 23, 'John', 43);
    print "Sorted by Keys \n
";
    foreach $key (sort keys %name)
    {
      print "$key: $name{$key}
";
    }
    print "Sorted by Values \n
";
    foreach $value (sort {$name{$a} cmp $name{$b} }keys %name)
    {
      print "$value: $name{$value}
";
    }

Result:

Sorted by Keys
     John: 43
     Jones: 23
     Peter: 51
     Tom: 26
Sorted by Values
     Jones: 23
     Tom: 26
     John: 43
     Peter: 51


Regular expressions are that makes Perl an ideal language for "Practical extraction and reporting" as the name implies.To construct the regular expression, which is essentially a sequence of characters describing the pattern you would like to match.

Metacharacter      Default Behaviour
\     Quote next character
^     Match beginning-of-string
.     Match any character except newline
$     Match end-of-string
|     Alternation
()     Grouping and save subpattern
[ ]     Character class


The split() function is used to split up a string using a regular expression delimiter or a character or a string.
Syntax:

     split (string);

In the above syntax, split() function takes a "string" as the argument.
Example to split string using regular expression delimiter:

    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    $str1 = "how,are,you";
    $str2 = "how!!are!!you";
    $str3 = "how1are2you";
    @val1 = split(",", $str1);
    @val2 = split('!!', $str2);
    @val3 = split(/\d+/, $str3);
    print "Removed the character Comma","\n";
    print "
";
    foreach $val1 (@val1)
     {
       print "$val1\n";
     }
    print "
";
    print "Removed the string '!!'";
    print "
";
    foreach $val2 (@val2)
     {
       print "$val2\n";
     }
    print "
";
    print "Removed the decimals 1,2";
    print "
";
    foreach $val3 (@val3)
     {
       print "$val3\n";
     }

Result:

    Removed the character Comma
    how are you
    Removed the string '!!'
    how are you
    Removed the decimals 1,2
    how are you

In the above example the string "howareyou" is seperated first with a comma, then by a string "!!", at last seperated by decimals "1,2", which is removed using a regular expression "/\d+/". All these strings are split and stored in an array, then using a loop its returned one by one.

Tuesday, February 16, 2010

C++ Class example

Basic Class C++ example code

// example one
#include
#include

class Book
{
// by default, all data and function are private

int PageCount;
int CurrentPage;
public:
Book( int Numpages) ; // Constructor
~Book(){} ; // Destructor
void SetPage( int PageNumber) ;
int GetCurrentPage( void ) ;
};

Book::Book( int NumPages) {
PageCount = NumPages;
}



void Book::SetPage( int PageNumber) {
CurrentPage=PageNumber;
}

int Book::GetCurrentPage( void ) {
return CurrentPage;
}

int main() {
Book ABook(128) ;   // Call constructor() and set PageNum=128
ABook.SetPage( 56 ) ;  // Set the current page number
std::cout << "Current Page " << ABook.GetCurrentPage() << std::endl;    // print out the current page
return 0;    // call destructor
}



This example will demonstrate inheritance. This is a two class  application  with one class derived from another.

    #include
    #include

    class Point
    {
   // default private
    int x,y;
    public:
    Point(int atx,int aty ) ; // Constructor
    inline virtual ~Point() ; // Destructor
    virtual void Draw() ;
    };




    class Circle : public Point {
    int radius;
    public:
    Circle(int atx,int aty,int theRadius) ;
    inline virtual ~Circle() ;
    virtual void Draw() ;
    };


    Point ::Point(int atx,int aty) {
    x = atx;
    y = aty;
    }

    inline Point::~Point ( void ) {
    std::cout << "Point Destructor called\n";
    }

    void Point::Draw( void ) {
    std::cout << "Point::Draw point at " << x << " " << y << std::endl;
    }


    Circle::Circle(int atx,int aty,int theRadius) : Point(atx,aty) {
    radius = theRadius;
    }

    inline Circle::~Circle() {
    std::cout << "Circle Destructor called" << std::endl;
    }

    void Circle::Draw( void ) {
    Point::Draw() ;
    std::cout << "circle::Draw point " << " Radius "<< radius << std::endl;
    }

    int main() {
    Circle ACircle(10,10,5) ;
    ACircle.Draw() ;
    return 0;
    }

What is Polymorphism?

Polymorphism is a generic term that means 'many shapes'. In C++ the simplest form of Polymorphism is overloading of functions, for instance several functions called SortArray( arraytype ) where sortarray might be an array  of ints, or doubles. 

/* A base class of Shape gives rise to
two derived classes - Circle and Square.

An application called Polygon sets up an
array of Circles and Squares, and uses a
getarea method to find the area of each.

This getarea method is defined as a virtual
method in the base class, so that an array
of shapes CAN be defined on which two
different getarea methods can be run
depending on which type of shape is the
current one at the time. */

::::::::::::::
shape.h
::::::::::::::

#ifndef SHAPE
#define SHAPE 1

class Shape {
        public:
                void setsize(int owbig);
                virtual float getarea() {};
        protected:
                int givensize;
        };

#endif
::::::::::::::
shape.cpp
::::::::::::::
#include "shape.h"

void Shape::setsize(int sv) {
        givensize = sv;
        }

::::::::::::::
square.h
::::::::::::::
#include "shape.h"

class Square: public Shape {
        public:
                float getarea();
        };
::::::::::::::
square.cpp
::::::::::::::
#include "square.h"

float Square::getarea() {
        float result = givensize * givensize;
        return (result);
        }
::::::::::::::
circle.h
::::::::::::::
#include "shape.h"

class Circle: public Shape {
        public:
                float getarea();
        };
::::::::::::::
circle.cpp
::::::::::::::
#include "circle.h"

float Circle::getarea() {
        float result = 3.14159265f * givensize;
        return result;
        }
::::::::::::::
polygon.cpp
::::::::::::::
#include
#include "circle.h"
#include "square.h"

main () {

        int np = 10;
        Shape *jigsaw[np];

        for (int k=0; k
                jigsaw[k] = new Square();
                jigsaw[k+1] = new Circle();
        }
        for (int k=0; k
                jigsaw[k]->setsize(10+k);
                }
        for (int k=0; k
                float syze = jigsaw[k]->getarea();
                cout << "this is sq " << syze << endl;
                }

        return (0);
        }

Perl interview questions Part #7

1) What happens when you return a reference to a private variable?

Answer:
Perl Keeps track of your variables, whether dynamic or otherwise, and dones't free things before you're done using them.

2) How do I sort a hash by the hash value?

Answer:

#!/usr/bin/perl -w
# help sort a hash by the hash 'value', not the 'key'

sub sorthashValueDescendingNum {$grades{$b} <=> ${grades{$a}};

%grades =( student1=>90,
student2=>75,
student3=>76);

print "\n\tGRADES IN ASCENDING NUMERIC ORDER\n";
foreach $key (sort(keys(%grades))){
print "\t\t$grades{$key} \t\t$key\n";
}

print "\n\tGRADES IN DESCENDING NUMERIC ORDER\n";
foreach $key (sorthashValueDescendingNum(keys(%grades))){
print "\t\t$grades{$key} \t\t$key\n";
}

3) How to read file into hash array?

Answer:

The following little snippet of code should do exactly what you want:

open(IN, "filename")

          or die "Couldn't open file for processing: $!";
while (
) {
chomp;
$hash_table{$_} = 0;
}
close IN;

Once you've read in your values, the following single line of code
will print them all out for you:

print "$_ = $hash_table{$_}\n" foreach keys %hash_table;


4) Does Perl have reference type?

Answer:

$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.

%hash=(key1=>vaule1,
             key2=>value2
);
$rhash-ref =\%hash;


4) How to initialize a hash?

Answer:
my %hash = ();    # initialize a hash
my $hash_ref = {};  # reference to empty hash

5) How to add data into hash?

Answer:
$hash{ 'key' } = 'value';    # hash

    $hash{ $key } = $value;      # hash, using variables

    $href->{ 'key' } = 'value';  # hash ref

    $href->{ $key } = $value;    # hash ref, using variables

    %hash = ( 'key1', 'value1', 'key2', 'value2', 'key3', 'value3' ); # add multiple items

    %hash = (
        key1 => 'value1',
        key2 => 'value2',
        key3 => 'value3',
    );

6) How to copy hash?

Answer:
   my %hash_copy = %hash;  # copy a hash

    my $href_copy = $href;  # copy a hash ref


7)  How to use while or for loop with Hash?


Use each within a while loop. Note that each iterates over entries in an apparently random order, but that order is guaranteed to be the same for the functions keys and values.

    while ( my ($key, $value) = each(%hash) ) {
        print "$key => $value\n";
    }


A hash reference would be only slightly different:

    while ( my ($key, $value) = each(%$hash_ref) ) {
        print "$key =>$value\n";
    }

Use keys with a for loop.

    for my $key ( keys %hash ) {
        my $value = $hash{$key};
        print "$key =>$value\n";
    }

8) What's the size of the hash?

Answer:
print "size of hash:  " . keys( %hash ) . ".\n";
 
 
Extra Hash information

Perl interview questions Part #6

1) Explain the difference between the following in Perl:
$array[3] vs $array->[3]

Answer:

$array[3] is the 4th element of the array "array"
$array->[3] is the hard reference to a (possible anonymous) array. It's the 4th element of the referenced array.


2) How to remove duplicates from an array?

Answer:

@array=(2,4,3,3,6,2);
my %seen=();
my @unique = grep { !seen{$_}++} @array;
print "@unique";

3) What is Perl on-liner?

Answer:
There are two ways a perl scripts can be run:
1. From a command line, called one-liner. It may contains many statements in one line.
e.g. perl -e "print \"Hello\";"

2. Script file, Perl program
e.g. perl program.pl

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