Time To Earn

Monday, November 18, 2013

Top 10 Questions of Java Strings

The following are top 10 frequently asked questions about Java Strings.

1. How to compare strings? Use “==” or use equals()?

In brief, “==” tests if references are equal and equals() tests if values are equal. Unless you want to check if two strings are the same object, you should always use equals().

It would be better if you know the concept of string interning.

2. Why is char[] preferred over String for security sensitive information?

Strings are immutable, which means once they are created, they will stay unchanged until Garbage Collector kicks in. With an array, you can explicitly change its elements. In this way, security sensitive information(e.g. password) will not be present anywhere in the system.

3. Can we use string for switch statement?

Yes to version 7. From JDK 7, we can use string as switch condition. Before version 6, we can not use string as switch condition.

view sourceprint?
01.
// java 7 only!
02.
switch (str.toLowerCase()) {
03.
case "a":
04.
value = 1;
05.
break;
06.
case "b":
07.
value = 2;
08.
break;
09.
}
4. How to convert string to int?

view sourceprint?
1.
int n = Integer.parseInt("10");
Simple, but so frequently used and sometimes ignored.

5. How to split a string with white space characters?

We can simple do split using regular expression. “\s” stands for white space characters such as ” “, “\t”, “\r”, “\n”.

view sourceprint?
1.
String[] strArray = aString.split("\\s+");
6. What substring() method does?

In JDK 6, the substring() method gives a window to an array of chars which represents the existing String, but do not create a new one. To create a new array to back string, you can do add an empty string like the following:
view sourceprint?
1.
str.substring(m, n) + ""
This will create a new char array that represents the new string. The above approach sometimes can make your code faster, because Garbage Collector can collect the unused large string and keep only the sub string.  In Oracle JDK 7, substring() creates a new char array, not uses the existing one. Check out the diagram for showing substring() difference between JDK 6 and JDK 7.
7. String vs StringBuilder vs StringBuffer

String vs StringBuilder: StringBuilder is mutable, which means you can modify it after its creation.
StringBuilder vs StringBuffer: StringBuffer is synchronized, which means it is thread-safe but slower than StringBuilder.

8. How to repeat a string?

In Python, we can just multiple a number to repeat a string. In Java, we can use the repeat() method of StringUtils from Apache Commons Lang package.

view sourceprint?
1.
String str = "abcd";
2.
String repeated = StringUtils.repeat(str,3);
3.
//abcdabcdabcd
9. How to convert string to date?

view sourceprint?
1.
String str = "Sep 17, 2013";
2.
Date date = new SimpleDateFormat("MMMM d, yy", Locale.ENGLISH).parse(str);
3.
System.out.println(date);
4.
//Tue Sep 17 00:00:00 EDT 2013
10. How to count # of occurrences of a character in a string?

Use StringUtils from apache commons lang.

view sourceprint?
1.
int n = StringUtils.countMatches("11112222", "1");
2.
System.out.println(n);

10 Java Exception and Error Interview Questions Answers

1) What is Exception in Java?
This is always been first interview question on Exception and mostly asked on fresher level interviews. I haven't seen anybody asking about what is Exception in senior and experienced level interviews, but this is quite popular at entry level. In simple word Exception is Java’s way to convey both system and programming errors. In Java Exception feature is implemented by using class like Throwable, Exception, RuntimeException and keywords like throw, throws, try, catch and finally. All Exception are derived form Throwable class. Throwable further divides errors in too category one is java.lang.Exception and other is java.lang.Error.  java.lang.Error deals with system errors like java.lang.StackOverFlowError or Java.lang.OutOfMemoryError while Exception is mostly used to deal with programming mistakes, non availability of requested resource etc.

2) What is difference between Checked and Unchecked Exception in Java ?
This is another popular Java Exception interview question appears in almost all level of Java interviews. Main difference between Checked and Unchecked Exception lies in there handling. Checked Exception requires to be handled at compile time using try, catch and finally keywords or else compiler will flag error. This is not a requirement for Unchecked Exceptions. Also all exceptions derived from java.lang.Exception classes are checked exception, exception those which extends RuntimeException, these are known as unchecked exception in Java. You can also check next article for more differences between Checked and Unchecked Exception.

3) What is similarity between NullPointerException and ArrayIndexOutOfBoundException in Java?
This is Java Exception interview question was not very popular, but appears in various fresher level interviews, to see whether candidate is familiar with concept of checked and unchecked exception or not. By the way answer of this interview question is both of them are example of unchecked exception and derived form RuntimeException. This question also opens door for difference of array in Java and C programming language, as arrays in C are unbounded and never throw ArrayIndexOutOfBoundException.

4) What best practices you follow while doing Exception handling in Java ?
This Exception interview question in Java is very popular while hiring senior java developer of Technical Lead. Since exception handling is crucial part of project design and good knowledge of this is desirable. There are lot of best practices, which can help to make your code robust and flexible at same time, here are few of them:

1) Returning boolean instead of returning null to avoid NullPointerException at callers end. Since NPE is most infamous of all Java exceptions, there are lot of techniques and coding best practices to minimize NullPointerException. You can check that link for some specific examples.

2) Non empty catch blocks. Empty catch blocks  are considered as one of the bad practices in Exception handling because they just ate Exception without any clue, at bare minimum print stack trace but you should do alternative operation which make sense or defined by requirements.

3) Prefer Unchecked exception over checked until you have a very good reason of not to do so. it improves readability of
code by removing boiler plate exception handling code
.
4) Never let your database Exception flowing till client error. since most of application deal with database and SQLException is a checked Exception in Java you should consider handling any database related errors in DAO layer of your application and only returning alternative value or something meaningful RuntimeException which client can understand and take action.

5) calling close() methods for connections, statements, and streams on finally block in Java.

I have already shared lot of these in my post Top 10 Java exception handling best practices, you can also refer that for more knowledge on this topic.

5) Why do you think Checked Exception exists in Java, since we can also convey error using RuntimeException ?
This is a controversial question and you need to be careful while answering this interview question. Though they will definitely like to hear your opinion, what they are mostly interested in convincing reason. One of the reason I see is that its a design decision, which is influenced by experience in programming language prior to Java e.g. C++. Most of checked exceptions are in java.io package, which make sense because if you request any system resource and its not available, than a robust program must be able to handle that situation gracefully. By declaring IOException as checked Exception, Java ensures that your provide that gracefully exception handling. Another possible reason could be to ensuring that system resources like file descriptors, which are limited in numbers, should be released as soon as you are done with that using catch or finally block. Effective Java book from Joshua Bloch has couple of items in this topic, which is again worth reading.

6) What is difference between throw and throws keyword in Java?
One more Java Exception interview questions from beginners kitty. throw and throws keyword may look quite similar, especially if you are new to Java programming and haven't seen much of it. Though they are similar in terms that both are used in Exception handling, they are different on how and where they are used in code. throws keyword is used in method signature to declare which checked exception method can throw, you can also declare unchecked exception, but that is not mandatory by compiler. This signifies lot of things like method is not going to handle Exception instead its throwing it, if method throws checked Exception then caller should provide compile time exception handling etc. On the other hand throw keyword is actually used to throw any Exception. Syntactically you can throw any Throwable (i.e. Throwable or any class derived from Throwable) , throw  keyword transfers control of execution to caller so it can be used in place of return keyword. Most common example of using throw in place of return is throwing UnSupportedOperationException from an empty method as shown below :

private static void show() {
    throw new UnsupportedOperationException("Not yet implemented");
}

See this article for more differences between these two keywords in Java.

7) What is Exception chaining in Java?
Exception chaining is a popular exception handling concept in Java, where another exception is thrown in response of an exception and creating a chain of Exceptions. This technique mostly used to wrap a checked exception into an unchecked or RuntimeException. By the way if you are throwing new exception due to another exception then always include original exception so that handler code can access root cause by using methods like getCause() and initCause().

8) Have you written your own custom Exception in Java? How do you do that?
Ofcourse most of us has written custom or business Exceptions like AccountNotFoundExcepiton. Main purpose of asking this Java Exception interview question is to find out how you use this feature. This can be used for sophisticated and precise exception handling with tweak involved in whether you would choose a checked or unchecked exception. By creating a specific exception for specific case, you also gives lot of options to caller to deal with them elegantly. I always prefer to have a precise exception than a general exception. Though creating lots of specific exceptions quickly increase number of classes in your project, maintaining a practical balance between specific and general exceptions are key to success.


9) What changes has been introduced in JDK7 related to Exception handling in Java ?
A relatively new and recent Exception interview question in Java. JDK7 has introduced two major feature which is related to Error and Exception handling,  one is ability to handle multiple exception in one catch block, popularly known as multi cache block and other is ARM blocks in Java 7 for automatic resource management, also known as try with resource. Both of these feature can certainly help to reduce boiler plate code required for handling checked exceptions in Java and significantly improves readability of code. Knowledge of this feature, not only helps to write better error and exception code in Java, but also helps to do well during interviews. I also recommend reading Java 7 Recipes book to get more insight on useful features introduced in Java 7, including these two.

10) Have you faced OutOfMemoryError in Java? How did you solved that?
This Java Error interview questions is mostly asked on senior level Java interviews and here interviewer is interested on your approach to tackle dangerous OutOfMemoryError. Admit it we always face this error no matter which kind of project you are working so if you say no it doesn't go very well with interviewer. I suggest even if you are not familiar or not faced it in reality but have 3 to 4 years of experience in Java, be prepare for it. At the same time, this is also a chance to impress interviewer by showing your advanced technical knowledge related to finding memory leaks, profiling and debugging. I have noticed that these skills almost always creates a positive impression. You can also see my post on how to fix java.lang.OutOfMemoryError for more detail on this topic.

11) Does code form finally executes if method returns before finally block or JVM exits ?
This Java exception interview question can also be asked in code format, where given a code with System.exit() in try block and something in finally block. It’s worth knowing that, finally block in Java executes even when return keyword is used in try block. Only time they don’t execute is when you call JVM to exit by executing System.exit(0)from try block in Java.


12) What is difference in final, finalize and finally keyword in Java?
Another classic interview question in core Java, this was asked to one of my friend on his telephonic interview for core Java developer with Morgan Stanley. final and finally are keyword, while finalize is method. final keyword is very useful for creating ad Immutable class in Java By making a class final, we prevent it from being extended, similarly by making a method final, we prevent it from being overridden,. On the other hand, finalize() method is called  by garbage collector, before that object is collected, but this is not guaranteed by Java specification. finally keyword is the only one which is related to error and exception handling and you should always have finally block in production code for closing connection and resources. See here for more detailed answer of this question.



13) What is wrong with following code :

 public static void start() throws IOException, RuntimeException{
    throw new RuntimeException("Not able to Start");
 }

 public static void main(String args[]) {
    try {
          start();
    } catch (Exception ex) {
            ex.printStackTrace();
    } catch (RuntimeException re) {
            re.printStackTrace();
    }
 }


This code will throw compiler error on line where RuntimeException  variable “re” is written on catch block. since Exception is super class of RuntimeException, all RuntimeException thrown by start() method will be captured by first catch block and code will never reach second catch block and that's the reason compiler will flag error as  “exception java.lang.RuntimeException has already been caught".


14) What is wrong with following code in Java:

public class SuperClass {
    public void start() throws IOException{
        throw new IOException("Not able to open file");
    }
}

public class SubClass extends SuperClass{
    public void start() throws Exception{
        throw new Exception("Not able to start");
    }
}

In this code compiler will complain on sub class where start() method gets overridden. As per rules of method overriding in Java, an overridden method can not throw Checked Exception which is higher in hierarchy than original method. Since here start() is throwing IOException in super class, start() in sub class can only throw either IOException or any sub class of IOException but not super class of IOException e.g. Exception.

15) What is wrong with following Java Exception code:

public static void start(){
   System.out.println("Java Exception interivew question Answers for Programmers");
}

public static void main(String args[]) {
   try{
      start();
   }catch(IOException ioe){
      ioe.printStackTrace();
   }
}
 
In this Java Exception example code, compiler will complain on line where we are handling IOException, since IOException is a checked Exception and start() method doesn't throw IOException, so compiler will flag error as "exception java.io.IOException is never thrown in body of corresponding try statement", but if you change IOException to Exception compiler error will disappear because Exception can be used to catch all RuntimeException which doesn't require declaration in throws clause. I like this little tricky Java Exception interview question because its not easy to figure out result by chaining IOException to Exception. You can also check Java Puzzlers by Joshua Bloch and Neil Gafter for some tricky questions based on Java Errors and Exceptions.

These are some of Java Error and Exception interview questions, I have mostly seen in both fresher and experienced level of Java interviews. There are a lot more questions on Exception which I haven't included and if you think you have a good question missed out than let me know and I will make effort to include it on this list of java exceptions question and answers. One last question of Java Exception I am leaving for you guys is "Why Java Exception considered to be better alternative of returning error codes" , let me know what is your thought on this list of Java Exception interview questions and answers.



Top 10 Tricky Java interview questions and Answers

What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always executed. This question challenge that concept by putting return statement in try or catch block or calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put return statement in try block or catch block but finally block won't run if you call System.exit form try or catch.

Can you override private or static method in Java ?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java.  Anyway, you can not override private or static method in Java, if you create similar method with same return type and same method arguments that's called method hiding. See Can you override private method in Java or more details.

Does Java support multiple inheritance ?
This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give. See Why multiple inheritance is not supported in Java to answer this tricky Java question.

What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys. See How HashMap works in Java for more tricky Java questions from HashMap.

If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. See Rules of method overriding in Java for more details.

What is the issue with following implementation of compareTo() method in Java

public int compareTo(Object o){
   Employee emp = (Employee) emp;
   return this.id - o.id;
}

where id is an integer number ?
Well three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can not guaranteed id is positive or negative. If id is negative than subtraction may overflow and produce incorrect result. See How to override compareTo method in Java for complete answer of this Java tricky question for experienced programmer.

How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. See how to avoid deadlock in Java for a sample code example.

What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.

What is difference between StringBuffer and StringBuilder in Java ?
Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

Can you access non static variable in static context?
Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java. Read why you can not access non-static variable from static method to learn more about this tricky Java questions.


Java Interview Questions - Part 1

1. What's the difference between an interface and an abstract class?
An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.
An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.
Abstract classes can have constants, members, method stubs and defined methods, whereas interfaces can only have constants and methods stubs.
Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.
When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don't have to be defined.
A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.
A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility.

2.  When to use abstract class or interface?
Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interfaca will have to declare and implement the methods listed by the interface.
If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that on mind before choosing.
Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.
Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contracts.

3.  What does the Serializable interface do ?

The Serializable interface is just a marker. It means that objects can be serialized, i.e. they can be represented as a bit string and restored from that bit string. For example, both of your classes are serializable because they can be represented as a bit string (or regular string). On the other hand, a class that represents a file handle given out by the operating system can not be serialized: As soon as the program is finished, that handle is gone, and there is no way to get it back. Reopening the file by file name is not guaranteed to work, since it may have been deleted/moved/changed permissions in the meantime.
Serializing objects that don't implement the Serializable interface will result in a NotSerializableException being thrown.

4. How you can force the garbage collection ?

Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.
Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.
Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

5 . What is Synchronization in Java?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time.
In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value.

6.  What is memory leak?

A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.

7. What is difference between stringbuffer and stringbuilder?
The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.
Criteria to choose among StringBuffer and StringBuilder
If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

8. What is the difference between checked and unchecked exceptions?
In general, unchecked exceptions represent defects in the program (bugs), which are normally Runtime exceptions.
Furthermore, checked exceptions represent invalid conditions in areas outside the immediate control of the program.

9.  How does Java allocate stack and heap memory?
 Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class).
In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.
In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.
The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code.

10. What is Java Reflection?
Reflection is commonly used by programs which require the ability to examine or modify the run time behavior of applications running in the Java virtual machine.


Saturday, November 16, 2013

Perl Most Ask Questions



What value is returned by a lone `return;' statement?
The undefined value in scalar context, and the empty list value () in list context.
This way functions that wish to return failure can just use a simple return without worrying about the context in which they were called.

What's the difference between /^Foo/s and /^Foo/?
The second would match Foo other than at the start of the record if $* were set.
The deprecated $* flag does double duty, filling the roles of both /s and /m. By using /s, you suppress any settings of that spooky variable, and force your carets and dollars to match only at the ends of the string and not at ends of line as well -- just as they would if $* weren't set at all.

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.

How to dereference a reference?
There are a number of ways to dereference a reference.
Using two dollar signs to dereference a scalar.
$original = $$strref;
Using @ sign to dereference an array.
@list = @$arrayref;
Similar for hashes.

What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?
5
length() is a built-in prototyped as sub length($), and a scalar prototype silently changes aggregates into radically different forms. The scalar sense of a hash is false (0) if it's empty, otherwise it's a string representing the fullness of the buckets, like "18/32" or "39/64". The length of that string is likely to be 5. Likewise, `length(@a)' would be 2 if there were 37 elements in @a.

If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}?
The second is disallowed under `use strict "refs"'.
Dereferencing a string with *{"STR"} is disallowed under the refs stricture, although *{STR} would not be. This is similar in spirit to the way ${"STR"} is always the symbol table variable, while ${STR} may be the lexical variable. If it's not a bareword, you're playing with the symbol table in a particular dynamic fashion.

How do I do < fill-in-the-blank > for each element in an array?
#!/usr/bin/perl -w
@homeRunHitters = ('McGwire', 'Sosa', 'Maris', 'Ruth');
foreach (@homeRunHitters) {
print "$_ hit a lot of home runs in one year\n";
}

How do I replace every <TAB> character in a file with a comma?

perl -pi.bak -e 's/\t/,/g' myfile.txt

What is the easiest way to download the contents of a URL with Perl?

Once you have the libwww-perl library, LWP.pm installed, the code is this:
#!/usr/bin/perl
use LWP::Simple;
$url = get 'http://www.websitename.com/';

How to concatenate strings with Perl?

Method #1 - using Perl's dot operator:
$name = 'checkbook';
$filename = "/tmp/" . $name . ".tmp";

Method #2 - using Perl's join function
$name = "checkbook";
$filename = join "", "/tmp/", $name, ".tmp";

Method #3 - usual way of concatenating strings
$filename = "/tmp/${name}.tmp";

How do I read command-line arguments with Perl?

With Perl, command-line arguments are stored in the array named @ARGV.
$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc.
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.
Here's a simple program:
#!/usr/bin/perl
$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";
foreach $argnum (0 .. $#ARGV) {
print "$ARGV[$argnum]\n";
}


When would `local $_' in a function ruin your day?
When your caller was in the middle for a while(m//g) loop
The /g state on a global variable is not protected by running local on it. That'll teach you to stop using locals. Too bad $_ can't be the target of a my() -- yet.

What happens to objects lost in "unreachable" memory, such as the object returned by Ob->new() in `{ my $ap; $ap = [ Ob->new(), \$ap ]; }' ?
Their destructors are called when that interpreter thread shuts down.
When the interpreter exits, it first does an exhaustive search looking for anything that it allocated. This allows Perl to be used in embedded and multithreaded applications safely, and furthermore guarantees correctness of object code.

Assume that $ref refers to a scalar, an array, a hash or to some nested data structure. Explain the following statements:
$$ref; # returns a scalar
$$ref[0]; # returns the first element of that array
$ref- > [0]; # returns the first element of that array
@$ref; # returns the contents of that array, or number of elements, in scalar context
$&$ref; # returns the last index in that array
$ref- > [0][5]; # returns the sixth element in the first row
@{$ref- > {key}} # returns the contents of the array that is the value of the key "key"


How do you match one letter in the current locale?
/[^\W_\d]/
We don't have full POSIX regexps, so you can't get at the isalpha() <ctype.h> macro save indirectly. You ask for one byte which is neither a non-alphanumunder, nor an under, nor a numeric. That leaves just the alphas, which is what you want.

How do I print the entire contents of an array with Perl?
To answer this question, we first need a sample array. Let's assume that you have an array that contains the name of baseball teams, like this:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
If you just want to print the array with the array members separated by blank spaces, you can just print the array like this:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
print "@teams\n";
But that's not usually the case. More often, you want each element printed on a separate line. To achieve this, you can use this code:
@teams = ('cubs', 'reds', 'yankees', 'dodgers');
foreach (@teams) {
print "$_\n";
}

Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical?
They are not identical. There are several differences between using single quotes and double quotes for strings.
1. The double-quoted string will perform variable interpolation on its contents. That is, any variable references inside the quotes will be replaced by the actual values.
2. The single-quoted string will print just like it is. It doesn't care the dollar signs.
3. The double-quoted string can contain the escape characters like newline, tab, carraige return, etc.
4. The single-quoted string can contain the escape sequences, like single quote, backward slash, etc.

How many ways can we express string in Perl?
Many. For example 'this is a string' can be expressed in:
"this is a string"
qq/this is a string like double-quoted string/
qq^this is a string like double-quoted string^
q/this is a string/
q&this is a string&
q(this is a string)

How do you give functions private variables that retain their values between calls?
Create a scope surrounding that sub that contains lexicals.
Only lexical variables are truly private, and they will persist even when their block exits if something still cares about them. Thus:
{ my $i = 0; sub next_i { $i++ } sub last_i { --$i } }
creates two functions that share a private variable. The $i variable will not be deallocated when its block goes away because next_i and last_i need to be able to access it.


------------------------------------

1) What are the two different types of data perl handles?
Perl handles two types of data they are
(i) Scalar Variables and
(ii) Lists
Scalar variables hold a single data item whereas lists hold multiple data items.

2) What are scalar variables?
Scalar variables are what many programming languages refer to as simple variables. They hold a single data item, a number, a string, or a perl reference. Scalars are called scalars to differentiate them from constructs that can hold more than one item, like arrays.

3) Explain about lists?
A list is a construct that associates data elements together and you can specify a list by enclosing those elements in parenthesis and separating them with commas. They could themselves be arrays, hashes or even other lists. Lists do not have a specific list data type.

4) Name all the prefix dereferencer in perl?
The symbol that starts all scalar variables is called a prefix dereferencer. The different types of dereferencer are.
(i) $-Scalar variables
(ii) %-Hash variables
(iii) @-arrays
(iv) &-subroutines
(v) Type globs-*myvar stands for @myvar, %myvar.
5) Explain about an ivalue?
An ivalue is an item that can serve as the target of an assignment. The term I value originally meant a “left value”, which is to say a value that appears on the left. An ivalue usually represents a data space in memory and you can store data using the ivalues name. Any variable can serve as an ivalue.
6) How does a “grep” function perform?
Grep returns the number of lines the expression is true. Grep returns a sublist of a list for which a specific criterion is true. This function often involves pattern matching. It modifies the elements in the original list.
7) Explain about Typeglobs?
Type globs are another integral type in perl. A typeglob`s prefix derefrencer is *, which is also the wild card character because you can use typeglobs to create an alias for all types associated with a particular name. All kinds of manipulations are possible with typeglobs.
8) Is there any way to add two arrays together?
Of course you can add two arrays together by using push function. The push function adds a value or values to the end of an array. The push function pushes the values of list onto the end of the array. Length of an array can be increased by the length of list.
9) How to use the command shift?
Shift array function shifts off the first value of the array and returns it, thereby shortening the array by one element and moving everything from one place to the left. If you don’t specify an array to shift, shift uses @ ARGV, the array of command line arguments passed to the script or the array named @-.
10) What exactly is grooving and shortening of the array?
You can change the number of elements in an array simply by changing the value of the last index of/in the array $#array. In fact, if you simply refer to a non existent element in an array perl extends the array as needed, creating new elements. It also includes new elements in its array.
11) What are the three ways to empty an array?
The three different ways to empty an array are as follows
1) You can empty an array by setting its length to a negative number.
2) Another way of empting an array is to assign the null list ().
3) Try to clear an array by setting it to undef, but be aware when you set to undef.

12) How do you work with array slices
An array slice is a section of an array that acts like a list, and you indicate what elements to put into the slice by using multiple array indexes in square brackets. By specifying the range operator you can also specify a slice.
13) What is meant by splicing arrays explain in context of list and scalar.
Splicing an array means adding elements from a list to that array, possibly replacing elements now in the array. In list context, the splice function returns the elements removed from the array. In scalar context, the splice function returns the last element removed.
14) What are the different types of perl operators?
There are four different types of perl operators they are
(i) Unary operator like the not operator
(ii) Binary operator like the addition operator
(iii) Tertiary operator like the conditional operator
(iv) List operator like the print operator
15) Which has the highest precedence, List or Terms? Explain?
Terms have the highest precedence in perl. Terms include variables, quotes, expressions in parenthesis etc. List operators have the same level of precedence as terms. Specifically, these operators have very strong left word precedence.
16) What is a short circuit operator?
The C-Style operator, ll, performs a logical (or) operation and you can use it to tie logical clauses together, returning an overall value of true if either clause is true. This operator is called a short-circuit operator because if the left operand is true the right operand is not checked or evaluated.

17) What are the different forms of goto in perl? Explain?
The three forms of goto are as follows. They are
(i) Goto label
(ii) Goto name
(iii) Goto expr
The first form, goto LABEL, transfers execution to the statement labeled LABEL. The second form, goto EXPR, expects EXPR to evaluate to a label. The last form goto &name is used with subroutines. This goto statement is used only when there is a necessity as it can create havoc in a program.
18) What are the different types of eval statements?
There are two different types of eval statements they are eval EXPR and eval BLOCK. Eval EXPR executes an expression and eval BLOCK executes BLOCK. Eval Block executes an entire block, BLOCK. First one is used when you want your code passed in the expression and the second one is used to parse the code in the block.
19) Determine the difference between my and local?
The fundamental difference between my and local is that my creates a new variable, whereas local saves a copy of an existing variable.
20) Explain about returning values from subroutines (functions)?
The return value of the subroutine is the value of the last expression evaluated or you can explicitly use a return statement to exit the subroutine specifying the return value. That return value is evaluated in the appropriate content depending on the content of the subroutine call.


--------------------------------

   1. Does Perl have reference type?

   2. How do I do < fill-in-the-blank > for each element in a hash?

   3. How do I do < fill-in-the-blank > for each element in an array?

   4. How do I do fill_in_the_blank for each file in a directory?

   5. How do I generate a list of all .html files in a directory?

   6. How do I print the entire contents of an array with Perl?



      -- Useful EBooks --

      How To Naturally Regrow Lost Hair


   7. How do I read command-line arguments with Perl?

   8. How do I replace every character in a file with a comma?

   9. How do I send e-mail from a Perl/CGI program on a Unix system?

  10. How do I set environment variables in Perl programs?

  11. How do I sort a hash by the hash key?

  12. How do I sort a hash by the hash value?

  13. How do you find the length of an array?

  14. How do you give functions private variables that retain their values between calls?

  15. How do you match one letter in the current locale?



      -- Useful EBooks --

      Weird Tricks to Lose Your Abdominal Fat


  16. How do you print out the next line from a filehandle with all its bytes reversed?

  17. How many ways can we express string in Perl?

  18. How to concatenate strings with Perl?

  19. How to dereference a reference?

  20. How to open and read data files with Perl

  21. How to read file into hash array ?

  22. How to read from a pipeline with Perl

  23. How to turn on Perl warnings? Why is that important?

  24. If EXPR is an arbitrary expression, what is the difference between $Foo::{EXPR} and *{"Foo::".EXPR}?

  25. Perl uses single or double quotes to surround a zero or more characters. Are the single(' ') or double quotes (" ") identical?

  26. What are scalar data and scalar variables?

  27. What does Perl do if you try to exploit the execve(2) race involving setuid scripts?

  28. What does `$result = f() .. g()' really return?

  29. What does `new $cur->{LINK}' do? (Assume the current package has no new() function of its own.)

  30. What does length(%HASH) produce if you have thirty-seven random keys in a newly created hash?

  31. What does read() return at end of file?

  32. What happens to objects lost in "unreachable" memory..... ?

  33. What happens when you return a reference to a private variable?

  34. What is the easiest way to download the contents of a URL with Perl?

  35. What value is returned by a lone `return;' statement?

  36. What's the difference between /^Foo/s and /^Foo/?

  37. When would `local $_' in a function ruin your day?

  38. Which of these is a difference between C++ and Perl?

  39. Why aren't Perl's patterns regular expressions?

  40. Why do you use Perl?

  41. Why does Perl not have overloaded functions?

  42. Why is it hard to call this function: sub y { "because" }

  43. Why should I use the -w argument with my Perl programs?

-----------------------

Question #2: Write a regular expression which matches a email address

Answer: This is very tricky question. Matching emails is not as trivial as it seems and the answer can be as simple as \w+@\w+\.[\w]{3}  or as messy as ^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}

Remember, it is interview question, not production code. So, be simple. I always recommend starting with basics:
\w+@\w+\.[\w]{3}

Then explain its limitations and give couple examples there the pattern would give false positive or false negative results. (such as test@test.111). From my experience, usually it is more than enough to impress interviewer.  From the other side, you always can iteratively enhance this pattern engaging interviewer into the conversation giving you the chance to showcase your knowledge.oo/?

  37. When would `local $_' in a function ruin your day?

  38. Which of these is a difference between C++ and Perl?

  39. Why aren't Perl's patterns regular expressions?

  40. Why do you use Perl?

  41. Why does Perl not have overloaded functions?

  42. Why is it hard to call this function: sub y { "because" }

  43. Why should I use the -w argument with my Perl programs?

-----------------------

Question #2: Write a regular expression which matches a email address

Answer: This is very tricky question. Matching emails is not as trivial as it seems and the answer can be as simple as \w+@\w+\.[\w]{3}  or as messy as ^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}

Remember, it is interview question, not production code. So, be simple. I always recommend starting with basics:
\w+@\w+\.[\w]{3}


Then explain its limitations and give couple examples there the pattern would give false positive or false negative results. (such as test@test.111). From my experience, usually it is more than enough to impress interviewer.  From the other side, you always can iteratively enhance this pattern engaging interviewer into the conversation giving you the chance to showcase your knowledge.