Git Interview Questions and Answer

git-interview-questions-and-answer

Q1. What is GIT?

Git is a distributed version control system and source code management (SCM) system with focus to handle small and large projects source code versions in the local repository with speed and efficiency. It is free and open source and its one of widly used versioning tools used ever worldwide.


Q2. What do you understant the repository in Git?

A repository in git, consists of .git directory which contains the each source code commited in form of objects created using SHA1 algorithms. A .git directry where git keeps all of its metadata for the source code in objects forms. It also contains the git configuration file, breanch reference and staging state of the work space.


Q. What is the command you can use to write a commit message?

The command that is used to write a commit message is “git commit –m”this is reason for commit”.  The –a on the command line instructs git to commit the new content of all tracked files that have been modified. You can use “git add <file>” before git commit –a if new files need to be committed for the first time.

In nutshell, any new changes has to added from working directory to stageing area and then commit from staging area to reposiory. Please refer the image for the same as below;


Q. What is the difference between GIT and SVN?

The difference between GIT and SVN is

  1. Git is less preferred for handling extremely large files or frequently changing binary files while SVN can handle multiple projects stored in the same repository.
  2. GIT does not support ‘commits’ across multiple branches or tags.  Subversion allows the creation of folders at any location in the repository layout.
  3. Gits are unchangeable, while Subversion allows committers to treat a tag as a branch and to create multiple revisions under a tag root.

Q. What are the advantages of using GIT?

  1. Data redundancy and replication
  2. High availability
  3. Only one.git directory per repository
  4. Superior disk utilization and network performance
  5. Collaboration friendly
  6. Any sort of projects can use GIT

Q. What language is used in GIT?

GIT is fast, and ‘C’ language makes this possible by reducing the overhead of runtimes associated with higher languages.


Q. What is the function of ‘GIT PUSH’ in GIT?

‘GIT PUSH’ updates remote refs along with associated objects.


Q. Why GIT better than Subversion?

GIT is an open source version control system; it will allow you to run ‘versions’ of a project, which show the changes that were made to the code overtime also it allows you keep the backtrack if necessary and undo those changes.  Multiple developers can checkout, and upload changes and each change can then be attributed to a specific developer.


Q. What is “Staging Area” or “Index” in GIT?

Before completing the commits, it can be formatted and reviewed in an intermediate area known as ‘Staging Area’ or ‘Index’.


Q. What is GIT stash?

GIT stash takes the current state of the working directory and index and puts in on the stack for later and gives you back a clean working directory.  So in case if you are in the middle of something and need to jump over to the other job, and at the same time you don’t want to lose your current edits then you can use GIT stash.

Q. What is GIT stash drop?

When you are done with the stashed item or want to remove it from the list, run the git ‘stash drop’ command.  It will remove the last added stash item by default, and it can also remove a specific item if you include as an argument.


Q. How will you know in GIT if a branch has been already merged into master?

Git branch—merged lists the branches that have been merged into the current branch

Git branch—no merged lists the branches that have not been merged


Q. is the function of git clone?

The git clone command creates a copy of an existing Git repository.  To get the copy of a central repository, ‘cloning’  is the most common way used by programmers.


Q. What is the function of ‘git config’?

The ‘git config’ command is a convenient way to set configuration options for your Git installation.  Behaviour of a repository, user info, preferences etc. can be defined through this command.


Q. What does commit object contain?

  1. A set of files, representing the state of a project at a given point of time
  2. Reference to parent commit objects
  3. An SHAI name, a 40 character string that uniquely identifies the commit object.

Q. How can you create a repository in Git?

In Git, to create a repository, create a directory for the project if it does not exist, and then run command “git init”. By running this command .git directory will be created in the project directory, the directory does not need to be empty.


Q. What is ‘head’ in git and how many heads can be created in a repository?

A ‘head’ is simply a reference to a commit object. In every repository, there is a default head referred as “Master”.  A repository can contain any number of heads.


Q. What is the purpose of branching in GIT?

The purpose of branching in GIT is that you can create your own branch and jump between those branches. It will allow you to go to your previous work keeping your recent work intact.


Q. What is the common branching pattern in GIT?

The common way of creating branch in GIT is to maintain one as “Main“

branch and create another branch to implement new features. This pattern is particularly useful when there are multiple developers working on a single project.


Q. How can you bring a new feature in the main branch?

To bring a new feature in the main branch, you can use a command “git merge” or “git pull command”.


Q. What is a ‘conflict’ in git?

A ‘conflict’ arises when the commit that has to be merged has some change in one place, and the current commit also has a change at the same place. Git will not be able to predict which change should take precedence.


Q. How can conflict in git resolved?

To resolve the conflict in git, edit the files to fix the conflicting changes and then add the resolved files by running “git add” after that to commit the repaired merge,  run “git commit”.  Git remembers that you are in the middle of a merger, so it sets the parents of the commit correctly.


Q. To delete a branch what is the command that is used?

Once your development branch is merged into the main branch, you don’t need development branch.  To delete a branch use, the command “git branch –d [head]”.


Q. What is another option for merging in git?

“Rebasing” is an alternative to merging in git.


Q. What is the syntax for “Rebasing” in Git?

The syntax used for rebase is “git rebase [new-commit] “


Q. What is the difference between ‘git remote’ and ‘git clone’?

‘git remote add’  just creates an entry in your git config that specifies a name for a particular URL.  While, ‘git clone’ creates a new git repository by copying and existing one located at the URI.


Q. What is GIT version control?

With the help of GIT version control, you can track the history of a collection of files and includes the functionality to revert the collection of files to another version.  Each version captures a snapshot of the file system at a certain point of time. A collection of files and their complete history are stored in a repository.


Q. Mention some of the best graphical GIT client for LINUX?

Some of the best GIT client for LINUX is

  1. Git Cola
  2. Git-g
  3. Smart git
  4. Giggle
  5. Git GUI
  6. qGit

Q. What is Subgit? Why to use Subgit?

‘Subgit’ is a tool for a smooth, stress-free SVN to Git migration.  Subgit is a solution for a company -wide migration from SVN to Git that is:

a)      It is much better than git-svn

b)      No requirement to change the infrastructure that is already placed

c)       Allows to use all git and all sub-version features

d)      Provides genuine stress –free migration experience.


Q. What is the function of ‘git diff ’ in git?

‘git diff ’ shows the changes between commits, commit and working tree etc.


Q. What is ‘git status’ is used for?

As ‘Git Status’ shows you the difference between the working directory and the index, it is helpful in understanding a git more comprehensively.


Q. What is the difference between the ‘git diff ’and ‘git status’?

‘git diff’ is similar to ‘git status’, but it shows the differences between various commits and also between the working directory and index.


Q. What is the function of ‘git checkout’ in git?

A ‘git checkout’ command is used to update directories or specific files in your working tree with those from another branch without merging it in the whole branch.


Q. What is the function of ‘git rm’?

To remove the file from the staging area and also off your disk ‘git rm’ is used.


Q. What is the function of ‘git stash apply’?

When you want to continue working where you have left your work, ‘git stash apply’ command is used to bring back the saved changes onto the working directory.


Q. What is the use of ‘git log’?

To find specific commits in your project history- by author, date, content or history ‘git log’ is used.


Q. What is ‘git add’ is used for?

‘git add’ adds file changes in your existing directory to your index.


Q. What is the function of ‘git reset’?

The function of ‘Git Reset’ is to reset your index as well as the working directory to the state of your last commit.


Q. What is git Is-tree?

‘git Is-tree’ represents a tree object including the mode and the name of each item and the SHA-1 value of the blob or the tree.


Q. How git instaweb is used?

‘Git Instaweb’ automatically directs a web browser and runs webserver with an interface into your local repository.


Q. What does ‘hooks’ consist of in git?

This directory consists of Shell scripts which are activated after running the corresponding Git commands.  For example, git will try to execute the post-commit script after you run a commit.


Q. Explain what is commit message?

Commit message is a feature of git which appears when you commit a change. Git provides you a text editor where you can enter the modifications made in commits.


Q. How can you fix a broken commit?

To fix any broken commit, you will use the command “git commit—amend”. By running this command, you can fix the broken commit message in the editor.


Q. Why is it advisable to create an additional commit rather than amending an existing commit?

There are couple of reason

  1. The amend operation will destroy the state that was previously saved in a commit.  If it’s just the commit message being changed then that’s not an issue.  But if the contents are being amended then chances of eliminating something important remains more.
  2. Abusing “git commit- amend” can cause a small commit to grow and acquire unrelated changes.

Q. What is ‘bare repository’ in GIT?

To co-ordinate with the distributed development and developers team, especially when you are working on a project from multiple computers ‘Bare Repository’ is used. A bare repository comprises of a version history of your code.


Q. How do you revert a commit that has already been pushed and made public?

One or more commits can be reverted through the use of git revert. This command, in essence, creates a new commit with patches that cancel out the changes introduced in specific commits. In case the commit that needs to be reverted has already been published or changing the repository history is not an option, git revert can be used to revert commits. Running the following command will revert the last two commits:

git revert HEAD~2..HEAD

Alternatively, one can always checkout the state of a particular commit from the past, and commit it anew.


Q. How do you squash last N commits into a single commit?

Squashing multiple commits into a single commit will overwrite history, and should be done with caution. However, this is useful when working in feature branches. To squash the last N commits of the current branch, run the following command (with {N} replaced with the number of commits that you want to squash):

git rebase -i HEAD~{N}

Upon running this command, an editor will open with a list of these N commit messages, one per line. Each of these lines will begin with the word “pick”. Replacing “pick” with “squash” or “s” will tell Git to combine the commit with the commit before it. To combine all N commits into one, set every commit in the list to be squash except the first one. Upon exiting the editor, and if no conflict arises, git rebase will allow you to create a new commit message for the new combined commit.


Q. How do you find a list of files that has changed in a particular commit?

git diff-tree -r {hash}

Given the commit hash, this will list all the files that were changed or added in that commit. The -r flag makes the command list individual files, rather than collapsing them into root directory names only.

The output will also include some extra information, which can be easily suppressed by including a couple of flags:

git diff-tree –no-commit-id –name-only -r {hash}

Here –no-commit-id will supress the commit hashes from appearing in the output, and –name-only will only print the file names, instead of their paths.


Q. How do you setup a script to run every time a repository receives new commits through push?

To configure a script to run every time a repository receives new commits through push, one needs to define either a pre-receive, update, or a post-receive hook depending on when exactly the script needs to be triggered.

Pre-receive hook in the destination repository is invoked when commits are pushed to it. Any script bound to this hook will be executed before any references are updated. This is a useful hook to run scripts that help enforce development policies.

Update hook works in a similar manner to pre-receive hook, and is also triggered before any updates are actually made. However, the update hook is called once for every commit that has been pushed to the destination repository.

Finally, post-receive hook in the repository is invoked after the updates have been accepted into the destination repository. This is an ideal place to configure simple deployment scripts, invoke some continuous integration systems, dispatch notification emails to repository maintainers, etc.

Hooks are local to every Git repository and are not versioned. Scripts can either be created within the hooks directory inside the “.git” directory, or they can be created elsewhere and links to those scripts can be placed within the directory.


Q. What is git bisect? How can you use it to determine the source of a (regression) bug?

Git provides a rather efficient mechanism to find bad commits. Instead of making the user try out every single commit to find out the first one that introduced some particular issue into the code, git bisect allows the user to perform a sort of binary search on the entire history of a repository.

By issuing the command git bisect start, the repository enters bisect mode. After this, all you have to do is identify a bad and a good commit:

git bisect bad # marks the current version as bad

git bisect good {hash or tag} # marks the given hash or tag as good, ideally of some earlier commit

Once this is done, Git will then have a range of commits that it needs to explore. At every step, it will checkout a certain commit from this range, and require you to identify it as good or bad. After which the range will be effectively halved, and the whole search will require a lot less number of steps than the actual number of commits involved in the range. Once the first bad commit has been found, or the bisect mode needs to be ended, the following command can be used to exit the mode and reset the bisection state:

git bisect reset


Q. What are the different ways you can refer to a commit?

In Git each commit is given a unique hash. These hashes can be used to identify the corresponding commits in various scenarios (such as while trying to checkout a particular state of the code using the git checkout {hash} command).

Additionally, Git also maintains a number of aliases to certain commits, known as refs. Also, every tag that you create in the repository effectively becomes a ref (and that is exactly why you can use tags instead of commit hashes in various git commands). Git also maintains a number of special aliases that change based on the state of the repository, such as HEAD, FETCH_HEAD, MERGE_HEAD, etc.

Git also allows commits to be referred as relative to one another. For example, HEAD~1 refers to the commit parent to HEAD, HEAD~2 refers to the grandparent of HEAD, and so on. In case of merge commits, where the commit has two parents, ^ can be used to select one of the two parents, e.g. HEAD^2 can be used to follow the second parent.

And finally, refspecs. These are used to map local and remote branches together. However, these can be used to refer to commits that reside on remote branches allowing one to control and manipulate them from a local Git environment.


Q. What is git rebase and how can it be used to resolve conflicts in a feature branch before merge?

In simple words, git rebase allows one to move the first commit of a branch to a new starting location. For example, if a feature branch was created from master, and since then the master branch has received new commits, git rebase can be used to move the feature branch to the tip of master. The command effectively will replay the changes made in the feature branch at the tip of master, allowing conflicts to be resolved in the process. When done with care, this will allow the feature branch to be merged into master with relative ease and sometimes as a simple fast-forward operation.


Q. How do you configure a Git repository to run code sanity checking tools right before making commits, and preventing them if the test fails?

This can be done with a simple script bound to the pre-commit hook of the repository. The pre-commit hook is triggered right before a commit is made, even before you are required to enter a commit message. In this script one can run other tools, such as linters and perform sanity checks on the changes being committed into the repository. For example, the following script:

#!/bin/sh
files=$(git diff –cached –name-only –diff-filter=ACM | grep ‘.go$’)
if [ -z files ]; then
exit 0
fi
unfmtd=$(gofmt -l $files)
if [ -z unfmtd ]; then
exit 0
fi
echo “Some .go files are not fmt’d”
exit 1

… checks to see if any .go file that is about to be commited needs to be passed through the standard Go source code formatting tool gofmt. By exiting with a non-zero status, the script effectively prevents the commit from being applied to the repository.

Tagged : / / / / / / / / / / /

Interview Questions and Answer for Perforce Version Control Tool

perforce-interview-questions-answers

Some of the perforce commands which is not commonly used but useful.
p4 annotate – Print file lines along with their revisions.
e.g p4 annotate file.c

How to ignore files/folder in perforce workspace/client?
Assuming you have a client named “CLIENT”, a directory named “foo” (located at your project root), and you wish to ignore all .dll files in that directory tree, you can add the following lines to your workspace view to accomplish this:

-//depot/foo/*.dll //CLIENT/foo/*.dll
-//depot/foo/…/*.dll //CLIENT/foo/…/*.dll

The first line removes them from the directory “foo” and the second line removes them from all sub directories. Now, when you ‘Reconcile Offline Work…’, all the .dll files will be moved into “Excluded Files” folders at the bottom of the folder diff display. They will be out of your way, but can still view and manipulate them if you really need to.

You can also do it another way, which will reduce your “Excluded Files” folder to just one, but you won’t be able to manipulate any of the files it contains because the path will be corrupt (but if you just want them out of your way, it doesn’t matter).

-//depot/foo.../*.dll //CLIENT/foo.../*.dll

Reference
How can I exclude a directory from a Perforce command?

P4IGNORE
Specify a file that contains a list of files to ignore when adding files to the depot and reconciling workspaces.
Reference

How to check last 10 submitted, pending, or shelved changelists that include any file under the project directory?
p4 changes -m 5 //depot/project/…

How to check last 10 submitted or pending, or shelved changelists that include any file under the project directory?
p4 changes -m 1 -s submitted | pending | shelved

Interview Questions Related to Perforce Admin

  1. How to take perforce backup
  2. How to restore perforce backup
  3. How to verify health of the perforce repos database
  4. What is the ise of p4 dbverify and p4 verify

What is the use of p4 admin commands.

The p4 admin command allows Perforce superusers to perform administrative tasks even when working from a different machine than the one running the shared Perforce service.
p4 [g-opts] admin checkpoint [ -z | -Z ] [ prefix ]
p4 [g-opts] admin journal [ -z ] [ prefix ]
p4 [g-opts] admin stop
p4 [g-opts] admin restart
p4 [g-opts] admin updatespecdepot [ -a | -s type ]
p4 [g-opts] admin resetpassword -a | -u user
Reference – Click here

How to remove files from perforce permanently?
p4 archive -p with caution. This is the one of only two commands in Perforce that actually removes file data. (The other command that removes file data is p4 obliterate.)

How to set properly in Perforce?
The Perforce service offers three ways of storing metadata: counters/keys, attributes, and properties.

If your application requires only the flat storage of simple key/value pairs, and attempts to implement no security model, use the p4 counters and p4 keys commands.

The p4 property command can be used by administrators to view and update property definitions stored in the Perforce service. The service does not use the property definitions; it provides this capability for other Perforce applications, such as P4V

If your application’s metadata is associated with particular files, use p4 attribute.

If your application’s metadata is not associated with files, and if you have a requirement to restrict its visibility to users, groups, and/or to control the precedence of multiple values using sequence numbers, use p4 property.

p4 property -n name -v value
p4 counter mycounter 123
p4 key mykey 12
p4 attribute -n name [ -v value ] files…

Perforce Integration with other Tools

  1. Gitfushion
  2. Swarm
  3. Replication
Tagged : / / / / / / / / / / / / / / /

Interview Questions & Answer for Build & Release Engineers

build-release-engineer-interview-questions-answer

I get many emails and linkedin personal message about sharing interview questions for Build & Release Engineer and Configuration Engineer.

I have asked some of my friends to share too and now here is the consolidated list of interview questions which is very much commonly asked in interview. if you like it, please share with other members and contribut it too. I will add in this article in next update. mail me at rajesh at scmgalaxy.com

Tag Line:

Interview Questions & Answer for Build Engineer
Interview Questions & Answer for Release Engineer
Interview Questions & Answer for Configuration Engineer
Interview Questions & Answer for Build & Release Engineer

Interview Questions and Answer on configuration management?

  • What do you think about configuration management?
  • What do you understand about Change Management?
  • branching methodologies and what currently theya re using it. Show with some example with pros and cons
  • Concept of Merging and Why do we need?

Interview Questions and Answer on build Management?

  • What do you think about build Management?
  • What are the key benefit of build Automation and what are the key inputs to automate the build process in the project?
  • Discuss about tools and technology which help to automate the entire build cycle.
  • What is Continuous Build Integration and How this is useful for the project?
  • What is daily build & nightly builds and what are the process need to set up to Automate & monitor consistently.
  • Explain in details for writing build sciprt for any project

Interview Questions and Answer on release Management?

  • What is release Management?
  • Talk about Release Management on several platforms?
  • What do you understand about Packaging and Deployment?
  • How to Automate Remote Deployment of Builds on Development & Test Servers?

Some Generic Interview questions for Build and Release and SCM Professionals.

  • What is workflow management. exmplain this in details
  • What do you understand about Code Coverage? Describe repective tools & utilities.
  • Describe the Integrate Packaging scripts & Test Automation scripts with build & Monitor build verification test status and tools.
  • How to co-ordinate with development team to increase their productiavity.
  • What do you understand about multisite project
  • How SCM team perform integration and co-ordination between Dev and QA
  • How do you Troubleshooting your build server. What kind of issues you get in build server or cm server?
  • java Comipler issues in build server and their version
  • C++ compiler issues in build server and their version
  • What are basic skills required for Perforce administration including Command Line info.
  • Explain the best practice for Setup process & maintain the Archive of software releases (internal & external) & license management of Third Party Libraries
  • Concept of labeling, branching and merging in perforce / svn and git
  • Best Practice and strategy of branching and merging in perforce
  • Talk about agile and attempts to minimize risk by developing software in short iterations.
  • Why agile on Iterative development model and Waterfall software development model?
  • What are Bug /Issue Tatcking tools available and descibe them.

Source code control best practice?

  • Use a reliable and dedicated server to house your code.
  • Backup your code daily.
  • Test your backup and restore processes.
  • Choose a source control tool that fits your organization’s requirements.
  • Perform all tool specific administrative tasks.
  • Keep your code repositories as clean as possible.
  • Secure access to your code.

Describe software build best practices?

  • Fully automated build process
  • Build repeatability
  • Build reproducibility
  • Build process adherence

Tools Comparison and Differences

  • Difference Between CVS and SVN
  • Difference Between perforce and SVN
  • Difference Between perforce and Clearcasee
  • Difference Between VSS and TFSC
  • Difference Between perforce and MKS
  • Difference Between Bea Weblogic and IBM Websphere
Tagged : / / / / / / / / / / / / / / /

Most asked Perl Interview Questions and Answers

perl-interview-questions-answers

What is Perl one-liner?

There are two ways a Perl script can be run:

a)from a command line, called one-liner, that means you type and execute immediately on the command line. You’ll need the -e option to start like “perl -e “print “Hello”;”. One-liner doesn’t mean one Perl statement. One-liner may contain many statements in one line.

b)from a script file, called Perl program.

Assuming both a local($var) and a my($var) exist, what’s the difference between ${var} and ${“var”}?

${var} is the lexical variable $var, and ${“var”} is the dynamic variable $var.

Note that because the second is a symbol table lookup, it is disallowed under `use strict “refs”‘. The words global, local, package, symbol table, and dynamic all refer to the kind of variables that local() affects, whereas the other sort, those governed by my(), are variously knows as private, lexical, or scoped variable.

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.

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.

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.

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.

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.

What are the different types of perl operators?

Please refer following URL..Perl Operators

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.

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.

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.

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.

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.

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.

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.

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.

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

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.

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.

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.

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.

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.

What is sed?
sed is stream editor, a Unix tool for working with streams of text data. See the awful truth about sed.

How do you substitute strings with sed?
Use ’s/old/new’ command, so sed ’s/hello/goodbye/’ would substitute the occurrence of the word hello to goodbye.

How do you inject text with sed?
& in the substitution string defines the pattern found in the search string. As an example, here’s us trying to find a word ‘hello’ and replacing it with ‘hello and how are you’:
echo ‘hello there’ | sed ’s/^hello/& and how are you/’

Can I find several patterns and refer to them in the replacement string?
Yes, use (pattern) and then refer to your patterns as \1, \2, \3 and so on.

If the string is ‘old old old’ and I run ’s/old/new’, I get ‘new old old’ as the result. I need ‘new new new‘.
You forgot the global modifier, which would replace every occurrence of the pattern with the substitution. ’s/old/new/g‘ will work.

But I want ‘old old new’ from the previous example. – Just use the numeric modifier saying you want the third occurrence to be replaced. ’s/old/new/3‘ will work.

I wrote a rather complex sed script. How do I save and run it?
Assuming that your file is named myscript1.sed, you can invoke sed -f myscript1.sed.

How do I delete trailing whitespaces from each line?
sed ’s/[ \t]*$//’ Here we’re replacing any occurrence of a space or a tab with nothing. Check sed one-liners for more examples.

How do you print just a few first lines of the file? – sed 1q will give you just the first line, sed 10q the first 10 lines.

How do you replace a pattern only if it’s found, so that it’s executed faster? – Nest the replacement statement: sed ‘/old/ s/old/new/g’ file.txt

How do you know the reference of a variable whether it is a reference,scaller, hash or array?
There is a ‘ref’ function that lets you know

What is the difference between ‘use’ and ‘require’ function?

Use: 1. the method is used only for modules (only to include .pm type file) 2. the included object are verified at the time of compilation. 3. No Need to give file extentsion. Require: 1. The method is used for both libraries ( package ) and modules 2. The include objects are varified at the run time. 3. Need to give file Extension.

What is the use of ‘chomp’ ? what is the difference between ‘chomp’ and ‘chop’?

Ans. ‘chop’ functiononly removes the last character completely ‘from the scaler, where as ‘chomp’ function only removes the last character if it is a newline. by default, chomp only removes what is currently defined as the $INPUT_RECORD_SEPARATOR. whenever you call ‘chomp ‘, it checks the value of a special variable ‘$/’. whatever the value of ‘$/’ is eliminated from the scaler. by default the value of ‘$/’ is ‘n’

Print this array @arr in reversed case-insensitive order

Ans> @solution = sort {lc $a comp lc$b } @arr.

What is ‘->’ in Perl?

Ans. it is a symbolic link to link one file name to a new name. so lets say we do it like file1-> file2, if we read file1, we end up reading file2.

how do you check the return code of system call?

System calls “traditionally” returns 9 when successful and 1 when it fails. system (cmd) or die “Error in command”;

#create directory if not there
if (! -s “$temp/engl_2/wf”){ System “mkdir -p $temp/engl_2/wf”; } if (! -s “$temp/backup_basedir”){ system “mkdir -p $temp/backup_basedir”; } ${pack_2} = -M “${temp}/engl_2/wf/${wf_package_name}.data”; ${new_pack}= -M “{pack}/package.data”; What is the use of -M and -s in the above script?

Ans. -s means is filename a non-empty file -M how long since filename modified?

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

Ans. perl -p -ibak -e ‘s/search_str/replace_str/g’ filename

I have a variable named $objref which is defined in main package. I want to make it as a Object of class XYZ. how could I do it?

Ans. use XYZ my $objref =XYZ -> new() OR, bless $objref, ‘XYZ’;

what is meant by a ‘pack’ in perl?

Pack Converts a list into a binary representation. Takes an array or list of values and packs it into a binary structure, returning the string containing the structure It takes a LIST of values and converts it into a string. The string contaings a con-catenation of the converted values. Typically, each converted values looks like its machine-level repesentation. for example, on 32-bit machines a converted integer may be representated by a sequence of 4 bytes.

how to implement stack in Perl?

through push() and shift() function. push adds the element at the last of array and shift() removes from the beginning of an array.

What is Grep used for in Perl?

Grep is used with regular expression to check if a parituclar value exist in an array. it returns 0 it the value does not exists, 1 otherwise.

How to code in Perl to implement the tail function in unix?

And. You have to maintain a structure to store the line number and the size of the file at that time eg. 1-10bytes, 2-18bytes.. you have a counter to increase the number of lines to find out the number of lines in the file. once you are through the file, you will know the size of the file at any nth line, use ‘sysseek’ to move the file pointer back to that position (last 10) and thens tart reading till the end.

15. How do you navigate thorugh an XML documents?

Ans. You can use the XML::DOM navigation methods to navigate thorugh an XML::DOM node tree and use the getnodevalue to recover the data. DOM Parser is used when it is neede to do node operation. Instead we may use SAX parser if you require simple processing of the xml structure.

Why do you use Perl?

* Perl is a powerful free interpreter.
* Perl is portable, flexible and easy to learn.

How do I set environment variables in Perl programs?

You can just do something like this:
$ENV{‘PATH’} = ‘…’;
As you may remember, “%ENV” is a special hash in Perl that contains the value of all your environment variables.
Because %ENV is a hash, you can set environment variables just as you’d set the value of any Perl hash variable. Here’s how you can set your PATH variable to make sure the following four directories are in your path::

$ENV{‘PATH’} = ‘/bin:/usr/bin:/usr/local/bin:/home/yourname/bin’;

Which of these is a difference between C++ and Perl?
Perl can have objects whose data cannot be accessed outside its class, but C++ cannot.

Perl can use closures with unreachable private data as objects, and C++ doesn’t support closures. Furthermore, C++ does support pointer arithmetic via `int *ip = (int*)&object’, allowing you do look all over the object. Perl doesn’t have pointer arithmetic. It also doesn’t allow `#define private public’ to change access rights to foreign objects. On the other hand, once you start poking around in /dev/mem, no one is safe.

How to open and read data files with Perl

Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.
As an example, suppose you need to read some data from a file named “checkbook.txt”. Here’s a simple open statement that opens the checkbook file for read access: open (CHECKBOOK, “checkbook.txt”); In this example, the name “CHECKBOOK” is the file handle that you’ll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named “CHECKBOOK”.
Now that we’ve opened the checkbook file, we’d like to be able to read what’s in it. Here’s how to read one line of data from the checkbook file:
$record = < CHECKBOOK > ;
After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The “<>” symbol is called the line reading operator.
To print every record of information from the checkbook file

open (CHECKBOOK, “checkbook.txt”) || die “couldn’t open the file!”;
while ($record = < CHECKBOOK >) {
print $record;
}
close(CHECKBOOK);

How do I do fill_in_the_blank for each file in a directory?
Answer:Here’s code that just prints a listing of every file in the current directory:
#!/usr/bin/perl -w
opendir(DIR, “.”);
@files = readdir(DIR);
closedir(DIR);
foreach $file (@files) {
print “$file\n”;
}

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

Answer:
Here’s a snippet of code that just prints a listing of every file in the current directory that ends with the extension .html:
#!/usr/bin/perl -w
opendir(DIR, “.”);
@files = grep(/\.html$/,readdir(DIR));
closedir(DIR);
foreach $file (@files) {
print “$file\n”;
}

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

Perl keeps track of your variables, whether dynamic or otherwise, and doesn’t free things before you’re done using them.

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

Perl is very forgiving of strange and sometimes wrong code, which can mean hours spent searching for bugs and weird results. Turning on warnings helps uncover common mistakes and strange places and save a lot of debugging time in the long run. There are various ways ofturning on Perl warnings:

* For Perl one-liner, use -w option on the command line.
* On Unix or Windows, use the -w option in the shebang line (The first # line in the script). Note: Windows Perl interpreter may not require it.
* For other systems, choose compiler warnings, or check compiler documentation.

What are scalar data and scalar variables?

Perl has a flexible concept of data types. Scalar means a single thing, like a number or string. So the Java concept of int, float, double and string equals to Perl\’s scalar in concept and the numbers and strings are exchangeable. Scalar variable is a Perl variable that is used to store scalar data. It uses a dollar sign $ and followed by one or more alphanumeric characters or underscores. It is case sensitive.

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

Many Perl developers use the -w option of the interpreter, especially during the development stages of an application. This warning option turns on many warning messages that can help you understand and debug your applications.
To use this option on Unix systems, just include it on the first line of the program, like this:
#!/usr/bin/perl -w
If you develop Perl apps on a DOS/Windows computer, and you’re creating a program named myApp.pl, you can turn on the warning messages when you run your program like this:
perl -w myApp.pl

I want users send data by formmail but when they send nothing or call it from web site they will see error. codes in PHP like this: if (isset($HTTP_POST_VARS)){ ………. } else{ echo (“error lalalalal”) } How it will look in perl?

In php it will be like
if (isset($HTTP_POST_VARS)){
….
}
In perl, tried this.
if ($ENV{‘REQUEST_METHOD’} eq ‘POST’){
…..
}

What is the output of the following Perl program?
1 $p1 = “prog1.java”;
2 $p1 =~ s/(.*)\.java/$1.cpp/;
3 print “$p1\n”;

Answer:What is the output of the following Perl program?
1 $p1 = “prog1.java”;
2 $p1 =~ s/(.*)\.java/$1.cpp/;
3 print “$p1\n”;

prog1.cpp

Why are not Perls patterns regular expressions?

Because Perl patterns have backreferences.
A regular expression by definition must be able to determine the next state in the finite automaton without requiring any extra memory to keep around previous state. A pattern /([ab]+)c\1/ requires the state machine to remember old states, and thus disqualifies such patterns as being regular expressions in the classic sense of the term.

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

Sends mail to root and exits.
It has been said that all programs advance to the point of being able to automatically read mail. While not quite at that point (well, without having a module loaded), Perl does at least automatically send it.

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

Here’s a simple technique to process each element in a hash:

#!/usr/bin/perl -w

%days = (
‘Sun’ =>’Sunday’,
‘Mon’ => ‘Monday’,
‘Tue’ => ‘Tuesday’,
‘Wed’ => ‘Wednesday’,
‘Thu’ => ‘Thursday’,
‘Fri’ => ‘Friday’,
‘Sat’ => ‘Saturday’ );

foreach $key (sort keys %days) {
print “The long name for $key is $days{$key}.\n”;
}

How do I sort a hash by the hash key?

Suppose we have a class of five students.
Their names are kim, al, rocky, chrisy, and jane.

Here’s a test program that prints the contents
of the grades hash, sorted by student name:

#!/usr/bin/perl -w

%grades = (
kim => 96,
al => 63,
rocky => 87,
chrisy => 96,
jane => 79,
);

print “\n\tGRADES SORTED BY STUDENT NAME:\n”;
foreach $key (sort (keys(%grades))) {
print “\t\t$key \t\t$grades{$key}\n”;
}

The output of this program looks like this:

GRADES SORTED BY STUDENT NAME:
al 63
chrisy 96
jane 79
kim 96
rocky 87

}

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

print scalar reverse scalar <FH>
Surprisingly enough, you have to put both the reverse and the <FH> into scalar context separately for this to work.

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

Sending e-mail from a Perl/CGI program on a Unix computer system is usually pretty simple. Most Perl programs directly invoke the Unix sendmail program. We’ll go through a quick example here.
Assuming that you’ve already have e-mail information you need, such as the send-to address and subject, you can use these next steps to generate and send the e-mail message:
# the rest of your program is up here …
open(MAIL, “|/usr/lib/sendmail -t”);
print MAIL “To: $sendToAddress\n”;
print MAIL “From: $myEmailAddress\n”;
print MAIL “Subject: $subject\n”;
print MAIL “This is the message body.\n”;
print MAIL “Put your message here in the body.\n”;
close (MAIL);

How to read from a pipeline with Perl
Example 1:

To run the date command from a Perl program, and read the output
of the command, all you need are a few lines of code like this:

open(DATE, “date|”);
$theDate = <DATE>;
close(DATE);

The open() function runs the external date command, then opens
a file handle DATE to the output of the date command.

Next, the output of the date command is read into
the variable $theDate through the file handle DATE.

Example 2:

The following code runs the “ps -f” command, and reads the output:

open(PS_F, “ps -f|”);
while (<PS_F>) {
($uid,$pid,$ppid,$restOfLine) = split;
# do whatever I want with the variables here …
}
close(PS_F);

Why is it hard to call this function: sub y { “because” }

Because y is a kind of quoting operator.
The y/// operator is the sed-savvy synonym for tr///. That means y(3) would be like tr(), which would be looking for a second string, as in tr/a-z/A-Z/, tr(a-z)(A-Z), or tr[a-z][A-Z].

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

False so long as f() returns false, after which it returns true until g() returns true, and then starts the cycle again.
This is scalar not list context, so we have the bistable flip-flop range operator famous in parsing of mail messages, as in `$in_body = /^$/ .. eof()’. Except for the first time f() returns true, g() is entirely ignored, and f() will be ignored while g() later when g() is evaluated. Double dot is the inclusive range operator, f() and g() will both be evaluated on the same record. If you don’t want that to happen, the exclusive range operator, triple dots, can be used instead. For extra credit, describe this:
$bingo = ( a() .. b() ) … ( c() .. d() );

Why does Perl not have overloaded functions?

Because you can inspect the argument count, return context, and object types all by yourself.
In Perl, the number of arguments is trivially available to a function via the scalar sense of @_, the return context via wantarray(), and the types of the arguments via ref() if they’re references and simple pattern matching like /^\d+$/ otherwise. In languages like C++ where you can’t do this, you simply must resort to overloading of functions.

What does read() return at end of file?

0
A defined (but false) 0 value is the proper indication of the end of file for read() and sysread().

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

$cur->new()->{LINK}
The indirect object syntax only has a single token lookahead. That means if new() is a method, it only grabs the very next token, not the entire following expression.
This is why `new $obj[23] arg’ does’t work, as well as why `print $fh[23] “stuff\n”‘ does’t work. Mixing notations between the OO and IO notations is perilous. If you always use arrow syntax for method calls, and nothing else, you’ll not be surprised.

How do I sort a hash by the hash value?

Here’s a program that prints the contents
of the grades hash, sorted numerically by the hash value:

#!/usr/bin/perl -w

# Help sort a hash by the hash ‘value’, not the ‘key’.
to highest).
sub hashValueAscendingNum {
$grades{$a} <=> $grades{$b};
}

# Help sort a hash by the hash ‘value’, not the ‘key’.
# Values are returned in descending numeric order
# (highest to lowest).
sub hashValueDescendingNum {
$grades{$b} <=> $grades{$a};
}

%grades = (
student1 => 90,
student2 => 75,
student3 => 96,
student4 => 55,
student5 => 76,
);

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

print “\n\tGRADES IN DESCENDING NUMERIC ORDER:\n”;
foreach $key (sort hashValueDescendingNum (keys(%grades))) {
print “\t\t$grades{$key} \t\t $key\n”;
}

How to read file into hash array ?

open(IN, “<name_file”)
or die “Couldn’t open file for processing: $!”;
while (<IN>) {
chomp;
$hash_table{$_} = 0;
}
close IN;

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

How do you find the length of an array?

$@array

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 is 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?
Answer:
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:
Answer:
$$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?

Answer:
/[^\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?
Answer:
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”;
}

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.

What is the Use of Symbolic Reference in PERL?

How to find type of variable?

What is Grep used for in Perl?

grep ( EXPR, LIST) extract any elements from LIST for which EXPR is TRUE.
Return Value

In scalar context – Number of times the expression returned true

In list context – List of elements that matched the expression

Example

Try out following example:

#!/usr/bin/perl

@list = (1,”Test”, 0, “foo”, 20 );

@has_digit = grep ( /\d/, @list );

print “@has_digit\n”;

It produces following result

1 0 20

What is eval in perl?

Evaluates EXPR at execution time as if EXPR were a separate Perl script. This allows you to use a separate, perhaps user-supplied, piece of Perl script within your program. An eval EXPR statement is evaluated separately each time the function is called.

The second form evaluates BLOCK when the rest of the script is parsed (before execution).

How to substitute a particular string in a file containing millions of records?

$_ = s/ string1 / string2 /g

How we can navigate the XML documents?

What is the difference between die and exit in perl?

Die is exmplained below;

exit Evaluates EXPR, exits the Perl interpreter, and returns the value as the exit value.Always runs all END{} blocks defined in the script (and imported packages) before exiting. If EXPR is omitted, then the interpreter exits with a value of 0. Should not be used to exit from a subroutine; either use eval and die or use return.

Following are the usage…

$ans = <STDIN>;
exit 0 if $ans =~ /^[Xx]/

What is hash in perl?

A hash represents a set of key/value pairs. Actaully hash are type of arrays with the exception that hash index could be a number or string. They are prefixed by % sign as follows:

my %fruit_color = (“apple”, “red”, “banana”, “yellow”);

what is meant ‘die’ in a perl program?

Raise an exception or bail out.

Following are the usage…

die “Can’t cd to spool: $!\n” unless chdir ‘/usr/spool/news’;
or
chdir ‘/usr/spool/news’ or die “Can’t cd to spool: $!\n”
or
open( FILEH, “>/tmp/test” ) || die( “Can’t open file test $!\n” );

what’s is the use of ‘require’ and what does this mean?

Load in external functions from a library at runtime

what does this mean ‘$^O’? tell briefly plse..

Contains the name of the operating system that the current Perl binary was compiled for.

what does this mean : ‘$_’ ?

$_ is a default special varible in perl which store the inputs for further pattern searching.

what are regular expressions?

A regular expression, also referred to as regex or regexp, provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters. A regular expression is written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification.

Difference between for and foreach?

Using for you can initialize variable, condition check and increment the variables like ‘C’ or like some other languages.
foreach is a function having in perl using you can iterates over the list and you cannot initialize or condition check or increment like ‘for’ in a single line.
We can use both for or foreach for any scenario but Perl author suggest that you can use for where you are counting a number of iteration like conventional for loops. foreach for list based operation where you are access the list from array.

Difference between exec and system in perl?

http://www.scmgalaxy.com/forum/perl-script/t-521.html#522

What is use strict. Explain with example.
strict – Perl pragma to restrict unsafe constructs.

Example:
use strict;
use strict “vars”;
use strict “refs”;
use strict “subs”;
use strict;
no strict “vars”;

use strict “subs”;
The use function allows you to use modules located in the standard liberary. When the strict pragma takes subs as an argument, it will catch any barewords found in the program while it is being internally compiled. If a bareword is found, the program will be aborted with an error message.

use strict “vars”
This generates a compile-time error if you access a variable that was neither explicitly declared (using any of my, our, state, or use vars ) nor fully qualified.

use strict “refs”
This generates a runtime error if you use symbolic references.

More –
http://perldoc.perl.org/strict.html
http://szabgab.com/barewords-in-perl.html

What is CPAN?
CPAN is the Comprehensive Perl Archive Network, a large collection of Perl software and documentation. You can begin exploring from either http://www.cpan.org/ or any of the mirrors listed at http://www.cpan.org/SITES.html.

CPAN is also the name of a Perl module, CPAN.pm, which is used to download and install Perl software from the CPAN archive.you may find the documentation for it by using perldoc CPAN via the command line
More: –
http://www.cpan.org/misc/cpan-faq.html#What_is_CPAN

How to install modules using CPAN or PPM (Perl Package Manager)
Install cpanm to make installing other modules easier
> cpan App::cpanminus (Mac OS X, Win32, X Windows/Linux)

Now install any module you can find in http://www.cpan.org/modules/index.html
cpanm Module::Name
such as to insall local::lib
> cpanm local::lib

ActiveState maintains repositories of precompiled CPAN packages that can be installed with either the PPM command-line client, or the PPM GUI application. To install the DBD-mysql database driver all you have to do is run the ppm install command:
> ppm install DBD-mysql

Alternatively you can run ppm without any parameters to invoke the GUI, search for DBD-mysql, select the DBD-mysql package, and perform the installation:
> ppm

How do you open a file for writing?

open(FH, "> $path") or die $!;

Difference between printf and sprintf in perl ? || print vs sprintf || Difference between print vs sprintf

The printf and sprintf is built-in function. One difference is printf prints it’s output and sprintf returns it’;s value.
Prints the value of LIST interpreted via the format specified by FORMAT to the current output filehandle, or to the one specified by FILEHANDLE.

Syntax
printf FILEHANDLE FORMAT, LIST
printf FORMAT, LIST

Return Value
0 on failure
1 on success

Effectively equivalent to print FILEHANDLE sprintf(FORMAT, LIST)

Try out following example:
#!/usr/bin/perl -w
printf “%d\n”, 3.1415126;
printf “The cost is \$%6.2f\n”,499;
printf “Perl’s version is v%vd\n”,%^V;
printf “%04d\n”, 20;

It will produce following results: Try more options yourself.
3
The cost is $499.00
Perl’s version is v
0020

On the other hand, The sprintf function uses FORMAT to return a formatted string based on the values in LIST. Essentially identical to printf, but the formatted string is returned instead of being printed.

Syntax
sprintf FORMAT, LIST

Return Value
SCALAR, a formatted text string.

Example
Try out following example:
#!/usr/bin/perl -w
$text = sprintf(“%0d \n”, 9);
print “Formated string $text\n”;

It will produce following result:
Formated string 9

What arguments do you frequently use for the Perl interpreter and what do they mean?
-w to show warning
-d to debug
-c to compile only not run
-e Which executes

You can check to see if your script has compiled successfully by using the –c switch. This used to check for syntax errors.
perl –c scriptname.pl

To Run on command line:executes the program given as an argument
perl –e ‘print “hello world\n”;’ unix/linux

With Warning Pragma
Perl –w <scriptname>

To start perl debugger on the file name specified as an argument
Perl –d <scriptname>

What do the symbols $ @ and % mean when prefixing a variable?
$  – To Define Scalar Variable
@ – To Define an Array
% – To define a hash

What elements of the Perl language could you use to structure your code to allow for maximum re-use and maximum readability?
It could be Subroutine, Module, Class, Package or objects. Questions should be more clear.

Why do you program in Perl?
Practice Report and Extraction Language
Interpreted Language optimized for scanning arbitrary test files, extracting information from them, and printing based on that information.
Very Powerful String handling features
Available for all platforms

Speed of Development
You can  enter the  program in a text file and just run it. It is an interpretive language; no compiler is neede
It is Powerful
The Regular expression of Perl are extremely powerful
Uses sophisticated pattern matching techniques to scan large amounts of data quickly.

Portability
Perl is a standard language and is available on all platforms.
Free version are available on the internet

Editing Perl programs
No sophisticated editing tool is needed
Any simple text editor like Notepad or vi will do

Flexibility
Perl Does not limit the size of your data
If Memory is available, perl can handle the whole file as a single string.
Allow one to write simple programs to perform complex task

What’s your favorite module and why?
use DBI;
use Getopt::Long;
use Time::Local;
use List::Compare;
use Log::Log4perl;
use CGI;
use HTML::Template;
use Data::Dumper;
use LWP;
use File::Find;

What is a hash?

A hash can be initialized with a list, where elements of the list are key and value pairs:

my %food_color = ( “Apple” => “red”, “Banana” => “yellow”, “Lemon” => “yellow”);

%age = ( “Nat”, 24, “Jules”, 25, “Josh”, 17 );
is equivalent to
$age{“Nat”} = 24; $age{“Jules”} = 25; $age{“Josh”} = 17;

$hash{“other”}

Only use the % when referring to the hash as a whole such as %boss
Hashes is that their elements are stored in an internal order convenient for efficient retrieval. it will come out in an unpredictable disorder.
When Referring to the value associated with a particular key, that’s a single scalar value, so is $ is called for.
When referring to one element of an array, you also use a $.
You can store only scalar value in a hash. References, however, are scalars. This solves the problem of storing multiple values for one key by making $hash{$key} a reference to an array containing values of $key.

What purpose does each of the following serve: -w?
Perl –w <scriptname>
Or
#! /usr/bin/perl –w
Or
use warnings; perl version 5.6 and later

The –w switch prints warnings about ambiguous identifiers, such as variables that have been used only once, improper conversion of stings and numbers etc

What is the difference between ‘use’ and ‘require’ function?
Use:
1. the method is used only for modules (only to include .pm type file)
2. the included object are verified at the time of compilation.
3. No Need to give file extentsion.
Require:
1. The method is used for both libraries ( package ) and modules
2. The include objects are varified at the run time.
3. Need to give file Extension.

Explain the difference between my and local.
Both of them are used to declare local variables.
The variables declared with “my” can live only within the block it was defined and cannot get its visibility inherited functions called within that block, but one defined with “local” can live within the block and have its visibility in the functions called within that block.

In the example below, $::a refers to $a in the ‘global’ namespace.

‘local’ temporarily changes the value of the variable, but only within the scope it exists in.

$a = 3.14159;
{
local $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}

print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs In block,

# This outputs

In block, $a = 3
In block, $::a = 3
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

‘my’ has no effect on the global $a, even inside the block.

$a = 3.14159;
{
my $a = 3;
print “In block, \$a = $a\n”;
print “In block, \$::a = $::a\n”;
}
print “Outside block, \$a = $a\n”;
print “Outside block, \$::a = $::a\n”;

# This outputs
In block, $a = 3
In block, $::a = 3.14159
Outside block, $a = 3.14159
Outside block, $::a = 3.14159

What is the difference between for & foreach?
What is the difference between exec & system?
What is the difference between map & grep?
What is the difference between sysread & read?
What is the difference between chop & chomp?
What is the difference between qq,qw & qx?
What is the difference between rand & srand?
What is the difference between exists and defined?
What is the difference between use and require?
What is the difference between eval & study?

Tagged : / / / / / / / / / / / / / / /

Apache Interview Questions – Apache Job Interview Kit

apche-interview-questions-answers

Apache Interview Questions – Apache Job Interview Kit

On a fresh install, why does Apache have three config files – srm.conf, access.conf and httpd.conf? – The first two are remnants from the NCSA times, and generally you should be ok if you delete the first two, and stick with httpd.conf.

What’s the command to stop Apache? – kill the specific process that httpd is running under, or killall httpd. If you have apachectl installed, use apachectl stop.

What does apachectl graceful do? – It sends a SIGUSR1 for a restart, and starts the apache server if it’s not running.
How do you check for the httpd.conf consistency and any errors in it? – apachectl configtest

When I do ps -aux, why do I have one copy of httpd running as root and the rest as nouser? – You need to be a root to attach yourself to any Unix port below 1024, and we need 80.

But I thought that running apache as a root is a security risk? – That one root process opens port 80, but never listens to it, so no user will actually enter the site with root rights. If you kill the root process, you will see the other kids disappear as well.

Why do I get the message “… no listening sockets available, shutting down”? – In Apache 2 you need to have a listen directive. Just put Listen 80 in httpd.conf.

How do you set up a virtual host in Apache?
<VirtualHost www.techinterviews.com>
ServerAdmin admin@techinterviews.com
DocumentRoot /home/apache/share/htdocs/hostedsites
ServerName www.techinterviews.com
ErrorLog /home/apache/logs/error/hostedsites/error_log
TransferLog /home/apache/logs/access/hostedsites/access_log
</VirtualHost>

What is ServerType directive? – It defines whether Apache should spawn itself as a child process (standalone) or keep everything in a single process (inetd). Keeping it inetd conserves resources. This is deprecated, however.

What is mod_vhost_alias? – It allows hosting multiple sites on the same server via simpler configurations.

What does htpasswd do? – It creates a new user in a specified group, and asks to specify a password for that user.
If you specify both deny from all and allow from all, what will be the default action of Apache? – In case of ambiguity deny always takes precedence over allow.

 

Tagged : / / / / / / / / / / / / / / / /

Maven Interview Questions and Answers – Maven Job Interview Kit

maven-interview-questions-answers

Maven Interview Questions and Answers

Contributed by Rajesh Kumar with the help of Google Search and www.scmGalaxy.com
Is there a way to use the current date in the POM?
Take a look at the buildnumber plugin. It can be used to generate a build date each time I do a build, as follows:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>maven-buildnumber-plugin</artifactId>
<version>0.9.4</version>
<configuration>
<format>{0,date,yyyy-MM-dd HH:mm:ss}</format>
<items>
<item>timestamp</item>
</items>
<doCheck>false</doCheck>
<doUpdate>false</doUpdate>
</configuration>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>create</goal>
</goals>
</execution>
</executions>
</plugin>

pom.xml or settings.xml? What is the best practice configuration usage for these files?
The best practice guideline between settings.xml and pom.xml is that configurations in settings.xml must be specific to the current user and that pom.xml configurations are specific to the project.
For example, <repositories> in pom.xml would tell all users of the project to use the <repositories> specified in the pom.xml. However, some users may prefer to use a mirror instead, so they’ll put <mirrors> in their settings.xml so they can choose a faster repository server.
so there you go:
settings.xml -> user scope
pom.xml -> project scope

How do I indicate array types in a MOJO configuration?

<tags>
    <tag>value1</tag>
    <tag>value2</tag>
  </tags>

How should I point a path for maven 2 to use a certain version of JDK when I have different versions of JDK installed on my PC and my JAVA_HOME already set?
If you don’t want to change your system JAVA_HOME, set it in maven script instead.
How do I setup the classpath of my antrun plugin to use the classpath from maven?
The maven classpaths are available as ant references when running your ant script. The ant reference names and some examples can be found here: maven-antrun-plugin
Is it possible to use HashMap as configurable parameter in a plugin? How do I configure that in pom.xml?
Yes. Its possible to use a HashMap field as a parameter in your plugin. To use it, your pom configuration should look like this:

<myMap>
      <yourkey>yourvalue</yourkey>
      .....
   </myMap>

How do I filter which classes should be put inside the packaged jar?
All compiled classes are always put into the packaged jar. However, you can configure the compiler plugin to exclude compiling some of the java sources using the compiler parameter excludes as follows:

<project>
   ...
   <build>
     ...
     <plugins>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <configuration>
           <excludes>
             <exclude>**/NotNeeded*.java</exclude>
           </excludes>
         </configuration>
       </plugin>
     </plugins>
     ...
   </build>
  </project>

How can I change the default location of the generated jar when I command “mvn package”?
By default, the location of the generated jar is in ${project.build.directory} or in your target directory.
We can change this by configuring the outputDirectory of maven-jar-plugin.

<plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-jar-plugin</artifactId>
              <configuration>
                  <outputDirectory>${project.build.directory}/<!-- directory --></outputDirectory>
              </configuration>
          </plugin>

How does maven 2 implement reproducibility?

  • Add the exact versions of plugins into your pluginDepenencies (make use of the release plugin)
  • Make use of ibiblio for your libraries. This should always be the case for jars. (The group is working on stabilising metadata and techniques for locking it down even if it changes. An internal repository mirror that doesn’t fetch updates (only new) is recommended for true reproducibility.)

Why there are no dependency properties in Maven 2?
They were removed because they aren’t reliable in a transitive environment. It implies that the dependency knows something about the
environment of the dependee, which is back to front. In most cases, granted, the value for war bundle will be the same for a particular
dependency – but that relies on the dependency specifying it.
In the end, we give control to the actual POM doing the building, trying to use sensible defaults that minimise what needs to be
specified, and allowing the use of artifact filters in the configuration of plugins.

What does aggregator mean in mojo?
When a Mojo has a @aggregator expression, it means that It can only build the parent project of your multi-module-project, the one who has the packaging of pom. It can also give you values for the expression ${reactorProjects} where reactorProjects are the MavenProject references to the parent pom modules.
Where is the plugin-registry.xml?
From the settings.xml, you may enable it by setting <usePluginRegistry/> to true
and the file will be in ~/.m2/plugin-registry.xml
How do I create a command line parameter (i.e., -Dname=value ) in my mojo?
In your mojo, put “expression=${<exp>}” in your parameter field

/**
   * @parameter expression="${expression.name}"
   */
  private String exp;

You may now able to pass parameter values to the command line.
“mvn -Dexpression.name=value install”
How do I convert my <reports> from Maven 1 to Maven 2?
In m1, we declare reports in the pom like this:

<project>
    ...
    <reports>
      <report>maven-checkstyle-plugin</report>
      <report>maven-pmd-plugin</report>
    </reports>
  </project>

In m2, the <reports> tag is replaced with <reporting>

<project>
    ...
    <reporting>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <configuration>
             <!-- put your config here -->
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-pmd-plugin</artifactId>
          <configuration>
             <!-- put your config here -->
          </configuration>
        </plugin>
      </plugins>
    <reporting>
  </project>

What does the “You cannot have two plugin executions with the same (or missing) elements” message mean?
It means that you have executed a plugin multiple times with the same <id>. Provide each <execution> with a unique <id> then it would be ok.
How do I add my generated sources to the compile path of Maven, when using modello?
Modello generate the sources in the generate-sources phase and automatically adds the source directory for compilation in maven. So you don’t have to copy the generated sources. You have to declare the modello-plugin in the build of your plugin for source generation (in that way the sources are generated each time).
What is Maven’s order of inheritance?

  1. parent pom
  2. project pom
  3. settings
  4. CLI parameters

where the last overrides the previous.
How do I execute the assembly plugin with different configurations?
Add this to your pom,

<build>
    ...
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
      <id>1</id>
            <phase>install</phase>
        <goals>
             <goal>assembly</goal>
       </goals>
          <configuration>
               <descriptor>src/main/descriptors/bin.xml</descriptor>
               <finalName>${project.build.finalName}-bin</finalName>
       </configuration>
          </execution>

<execution>
<id>2</id>
<phase>install</phase>
<goals>
<goal>assembly</goal>
</goals>
<configuration>
<descriptor>src/main/descriptors/src.xml</descriptor>
<finalName>${project.build.finalName}-src</finalName>
</configuration>
</execution>
</executions>
</plugin>
</plugins>

</build>

and run mvn install, this will execute the assembly plugin twice with different config.
How do I configure the equivalent of maven.war.src of war plugin in Maven 2.0?

<build>
    ...
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
           <warSourceDirectory><!-- put the path of the directory --></warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
    ...
  </build>

How do I add main class in a generated jar’s manifest?
Configure the maven-jar-plugin and add your main class.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
     <mainClass>com.mycompany.app.App</mainClass>
        </manifest>
      </archive>
    </configuration>
  </plugin>

What does the FATAL ERROR with the message “Class org.apache.commons.logging.impl.Jdk14Logger does not implement Log” when using the maven-checkstyle-plugin mean?
Checkstyle uses commons-logging, which has classloader problems when initialized within a Maven plugin’s container. This results in the above message – if you run with ‘-e’, you’ll see something like the following:

Caused by: org.apache.commons.logging.LogConfigurationException: org.apache.commons.logging.LogConfigurationException: Class org.apache.commons.logging.impl.Jdk14Logger does not implement Log

buried deep in the stacktrace.
The only workaround we currently have for this problem is to include another commons-logging Log implementation in the plugin itself. So, you can solve the problem by adding the following to your plugin declaration in your POM:

<project>
    ...
    <build>
      ...
      <plugins>
        ...
        <plugin>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <dependencies>
            <dependency>
              <groupId>log4j</groupId>
              <artifactId>log4j</artifactId>
              <version>1.2.12</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </build>
    ...
    <reporting>
      ...
      <plugins>
        <!-- your checkstyle report is registered here, according to Maven documentation -->
      </plugins>
    </reporting>
  </project>

While this may seem a counter-intuitive way of configuring a report, it’s important to remember that Maven plugins can have a mix of reports and normal mojos. When a POM has to configure extra dependencies for a plugin, it should do so in the normal plugins section.
We will probably try to fix this problem before the next release of the checkstyle plugin.
UPDATE: This problem has been fixed in the SVN trunk version of the checkstyle plugin, which should be released very soon.
Plugins and Lifecycle, Sites & Reporting, Errors
How do I determine the stale resources in a Mojo to avoid reprocessing them?
This can be done using the following piece of code:

// Imports needed
  import org.codehaus.plexus.compiler.util.scan.InclusionScanException;
  import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner;
  import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping;

// At some point of your code
StaleSourceScanner scanner = new StaleSourceScanner( 0, Collections.singleton( “**/*.xml” ), Collections.EMPTY_SET );
scanner.addSourceMapping( new SuffixMapping( “.xml”, “.html” ) );
Set<File> staleFiles = (Set<File>) scanner.getIncludedSources( this.sourceDirectory, this.targetDirectory );

The second parameter to the StaleSourceScanner is the set of includes, while the third parameter is the set of excludes. You must add a source mapping to the scanner (second line). In this case we’re telling the scanner what is the extension of the result file (.html) for each source file extension (.xml). Finally we get the stale files as a Set<File> calling the getIncludedSources method, passing as parameters the source and target directories (of type File). The Maven API doesn’t support generics, but you may cast it that way if you’re using them.
In order to use this API you must include the following dependency in your pom:

<dependencies>
    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-compiler-api</artifactId>
      <version>1.5.1</version>
    </dependency>
  </dependencies>

Is there a property file for plug-in configuration in Maven 2.0?
No. Maven 2.x no longer supports plug-in configuration via properties files. Instead, in Maven 2.0 you can configure plug-ins directly from command line using the -D arguement, or from the plug-in’s POM using the <configuration> element.
How do I determine which POM contains missing transitive dependency?
run “mvn -X”
How do I integrate static (x) html into my Maven site?
You can integrate your static pages in this several steps,

  • Put your static pages in the resources directory, ${basedir}/src/site/resources.
  • Create your site.xml and put it in ${basedir}/src/site. An example below:
<project name="Maven War Plugin">
    <bannerLeft>
      <name>Maven War Plugin</name>
      <src>http://maven.apache.org/images/apache-maven-project.png</src>
      <href>http://maven.apache.org/</href>
    </bannerLeft>
    <bannerRight>
      <src>http://maven.apache.org/images/maven-small.gif</src>
    </bannerRight>
    <body>
      <links>
        <item name="Maven 2" xhref="http://maven.apache.org/maven2/"/>
      </links>

<menu name=”Overview”>
<item name=”Introduction” xhref=”introduction.html”/>
<item name=”How to Use” xhref=”howto.html”/>
</menu>
${reports}
</body>
</project>

Link the static pages by modifying the <menu> section, create items and map it with the filename of the static pages.

<menu name="Overview">
    <item name="Introduction" xhref="introduction.html"/>
    <item name="How to Use" xhref="howto.html"/>
    <item name="<put-name-here>" xhref="<filename-of-the-static-page>"/>
  </menu>

How do I run an ant task twice, against two different phases?
You can specify multiple execution elements under the executions tag, giving each a different id and binding them at different phases.

<plugin>
         <artifactId>maven-antrun-plugin</artifactId>
         <executions>
           <execution>
              * <id>one</id>*
             <phase>generate-sources</phase>
             <configuration>
               <tasks>
                 <echo message="generate-sources!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"/>
               </tasks>
             </configuration>
             <goals>
               <goal>run</goal>
             </goals>
           </execution>

<execution>
*<id>two</id>*
<phase>package</phase>
<configuration>
<tasks>
* <echo message=”package!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!”/>*

</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>

Can a profile inherit the configuration of a “sibling” profile?
No. Profiles merge when their ID’s match – so you can inherit them from a parent POM (but you can’t inherit profiles from the same POM).
Inheritence and Interpolation, Plugins and Lifecycle, POM
How do I invoke the “maven dist” function from Maven 1.0, in Maven 2.0?
mvn assembly:assembly
See the Assembly Plugin documentation for more details.
General, Plugins and Lifecycle
How do I specify which output folders the Eclipse plugin puts into the .classpath file?

<build>
  ...
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-eclipse-plugin</artifactId>
          <configuration>
            <outputDirectory>target-eclipse</outputDirectory>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  ...
  </build>

What is a Mojo?
A mojo is a Maven plain Old Java Object. Each mojo is an executable goal in Maven, and a plugin is a distribution of one or more related mojos.
How to produce execution debug output or error messages?
You could call Maven with -X parameter or -e parameter. For more information, run:

mvn --help

Maven compiles my test classes but doesn’t run them?
Tests are run by the surefire plugin. The surefire plugin can be configured to run certain test classes and you may have unintentionally done so by specifying a value to ${test}. Check your settings.xml and pom.xml for a property named “test” which would like this:

  ...
    <properties>
      <property>
        <name>test</name>
        <value>some-value</value>
      </property>
   </properties>
    ...

Or

  ...
    <properties>
      <test>some-value</test>
   </properties>
    ...

How do I include tools.jar in my dependencies?
The following code includes tools.jar on Sun JDKs (it is already included in the runtime for Mac OS X and some free JDKs).

...
    <profiles>
      <profile>
        <id>default-tools.jar</id>
        <activation>
          <property>
            <name>java.vendor</name>
            <value>Sun Microsystems Inc.</value>
         </property>
       </activation>
        <dependencies>
          <dependency>
            <groupId>com.sun</groupId>
            <artifactId>tools</artifactId>
            <version>1.4.2</version>
            <scope>system</scope>
            <systemPath>${java.home}/../lib/tools.jar</systemPath>
         </dependency>
       </dependencies>
     </profile>
   </profiles>
    ...

I have a jar that I want to put into my local repository. How can I copy it in?
If you understand the layout of the maven repository, you can copy the jar directly into where it is meant to go. Maven will find this file next time it is run.
If you are not confident about the layout of the maven repository, then you can adapt the following command to load in your jar file, all on one line.

mvn install:install-file
    -Dfile=<path-to-file>
    -DgroupId=<group-id>
    -DartifactId=<artifact-id>
    -Dversion=<version>
    -Dpackaging=<packaging>
    -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
<group-id>      the group that the file should be registered under
<artifact-id>   the artifact name for the file
<version>       the version of the file
<packaging>     the packaging of the file e.g. jar

This should load in the file into the maven repository, renaming it as needed.
How do I set up Maven so it will compile with a target and source JVM of my choice?
You must configure the source and target parameters in your pom. For example, to set the source and target JVM to 1.5, you should have in your pom :

...
    <build>
    ...
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.0.2</version>
          <configuration>
            <source>1.5</source>
            <target>1.5</target>
         </configuration>
       </plugin>
     </plugins>
    ...
   </build>
    ...

How can I use Ant tasks in Maven 2?

There are currently 2 alternatives:

Maven 2.0 Eclipse Plug-in

Plugins are great in simplifying the life of programmers; it actually reduces the repetitive tasks involved in the programming. In this article our experts will show you the steps required to download and install the Maven Plugin with your eclipse IDE.
Why Maven with Eclipse
Eclipse is an industry leader in IDE market, it is used very extensively in developing projects all around the world. Similarly, Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management.

Maven–Eclipse Integration makes the development, testing, packaging and deployment process easy and fast. Maven Integration for Eclipse provides a tight integration for Maven into the IDE and avails the following features:
· It helps to launch Maven builds from within Eclipse
· It avails the dependency management for Eclipse build path based on Maven’s pom.xml
· It resolves Maven dependencies from the Eclipse workspace withoutinstalling to local Maven repository
· It avails an automatic downloading of the required dependencies from the remote Maven repositories
· It provides wizards for creating new Maven projects, pom.xml or to enable Maven support on plain Java project
· It helps to search quickly for dependencies in Maven remote repositories
· It quickly fixes in the Java editor for looking up required dependencies/jars by the class or package name.
What do you Need?
1. Get the Eclipse Development Environment :
In this tutorial we are using the eclipse-SDK-3.3-win32, which can be downloaded fromhttp://www.eclipse.org/downloads/
2. Get Maven-eclipse-plugin-plugin :
It is available at http://mevenide.codehaus.org/maven-eclipse-plugin-plugin/

Download and Install Eclipse
First download and install the eclipse plugin on your development machine then proceed with the installation process of the eclipse-maven plugin.

A Maven 2.0 Repository: An Introduction

Maven repository Types:

  • Public remote external repository: This public external repository exists at ibiblio.org and maven synchronizes with this repository.
  • Private remote internal repository: We set up this repository and make changes in the maven’s pom.xml or settings.xml file to use this repository.
  • Local repository: This repository is maintained by the developer and stays on the developer’s machine. It is synchronous to the maven repository defined in the settings.xml file that exists in the .m2 directory at its standard location i.e. C:\Documents and Settings\Administrator. If no private internal repository is setup and not listed in the pom.xml or in the setting.xml then the local repository exists on the developer’s machine is synchronized with the public maven repository at ibiblio.org.

Advantages of having an internal private repository :

  • Reduces conflicts among likelihood versions.
  • To build first time it requires less manual intervention.
  • Rather than having several separate independent libraries it provides a single central reference repository for all the dependent software libraries.
  • It quickly builds the project while using an internal repository as maven artifacts are retrieved from the intranet server rather than retrieving from the server on internet.

Use cases for maven repository:

  • It creates two sub-repository inside the internal repository.
  • Downloads ibiblio-cache from ibiblio for artifacts and make it available publically. This synchronizes with external repository from ibiblio.
  • internal-maven-repository: used for internal artifacts of an organization. It contains unique artifacts for the organization and is not synchronized with any repository.
  • Alternatively, another sub-repository that is not at ibiblio can be created for artifacts. This does not synchronize with any external repository.
  • Browse the remote repository by using a web browser.
  • Search the artifacts in the repository.
  • Download code from version control and make changes in settings.xml to point to the internal repository and build without any manual intervention.
  • Install new version of the artifacts.
  • Import artifacts into the repository in bulk.
  • Export artifacts from the repository in bulk.
  • Setup the task to backup the repository automatically.

Criteria for choosing a maven repository implementation: In ideal condition a maven repository implementation should be:

  • Free and open source
  • Provide admin tools
  • Easy to setup and use
  • Provide backup facility
  • Able to create, edit and delete sub repositories.
  • Anonymous read only access and also access control facility.
  • Deployable in any standard web server such as Tomcat or Apache.
  • Issue tracker, forums and other independent source of information.
  • Active community developers make the product enhanced and bugs fixed.
  • Bulk import/export facility to move groups of artifacts into the repository and out of the repository.
  • Provide a repository browser: should be a web browser instead of the desktop application.

Shifting from Apache Ant to Maven

Maven is entirely a different creature from Ant. Ant is simply a toolbox whereas Maven is about the application of patterns in order to achieve an infrastructure which displays the characteristics of visibility, reusability, maintainability, and comprehensibility. It is wrong to consider Maven as a build tool and just a replacement for Ant.
Ant Vs Maven
There is nothing that Maven does that Ant cannot do. Ant gives the ultimate power and flexibility in build and deployment to the developer. But Maven adds a layer of abstraction above Ant (and uses Jelly). Maven can be used to build any Java application. Today JEE build and deployment has become much standardized. Every enterprise has some variations, but in general it is all the same: deploying EARs, WARs, and EJB-JARs. Maven captures this intelligence and lets you achieve the build and deployment in about 5-6 lines of Maven script compared to dozens of lines in an Ant build script.
Ant lets you do any variations you want, but requires a lot of scripting. Maven on the other hand mandates certain directories and file names, but it provides plugins to make life easier. The restriction imposed by Maven is that only one artifact is generated per project (A project in Maven terminology is a folder with a project.xml file in it). A Maven project can have sub projects. Each sub project can build its own artifact. The topmost project can aggregate the artifacts into a larger one. This is synonymous to jars and wars put together to form an EAR. Maven also provides inheritance in projects.
Maven : Stealing the show
Maven simplifies build enormously by imposing certain fixed file names and acceptable restrictions like one artifact per project. Artifacts are treated as files on your computer by the build script. Maven hides the fact that everything is a file and forces you to think and script to create a deployable artifact such as an EAR. Artifact has a dependency on a particular version of a third party library residing in a shared remote (or local) enterprise repository, and then publish your library into the repository as well for others to use. Hence there are no more classpath issues. No more mismatch in libraries. It also gives the power to embed even the Ant scripts within Maven scripts if absolutely essential.

Maven 2.0: Features

Maven is a high-level, intelligent project management, build and deployment tool provided by Apache’s software foundation group. Maven deals with application development lifecycle management. Maven was originally developed to manage and to minimize the complexities of building the Jakarta Turbine project. But its powerful capabilities have made it a core entity of the Apache Software Foundation projects. Actually, for a long time there was a need to standardized project development lifecycle management system and Maven has emerged as a perfect option that meets the needs. Maven has become the de- facto build system in many open source initiatives and it is rapidly being adopted by many software development organizations.
Maven was borne of the very practical desire to make several projects at Apache work in a consistence manner. So that developers could freely move between these projects, knowing clearly how they all worked by understanding how one of them worked.

If a developer spent time understanding how one project built it was intended that they would not have to go through this process again when they moved on to the next project. The same idea extends to testing, generating documentation, generating metrics and reports, testing and deploying. All projects share enough of the same characteristics, an understanding of which Maven tries to harness in its general approach to project management.
On a very high level all projects need to be built, tested, packaged, documented and deployed. There occurs infinite variation in each of the above mentioned steps, but these variation still occur within the confines of a well defined path and it is this path that Maven attempts to present to everyone in a clear way. The easiest way to make a path clear is to provide people with a set of patterns that can be shared by anyone involved in a project.

The key benefit of this approach is that developers can follow one consistent build lifecycle management process without having to reinvent such processes again. Ultimately this makes developers more productive, agile, disciplined, and focused on the work at hand rather than spending time and effort doing grunt work understanding, developing, and configuring yet another non-standard build system.
Maven: Features

  1. Portable: Maven is portable in nature because it includes:
    • Building configuration using maven are portable to another machine, developer and architecture without any effort
    • Non trivial: Maven is non trivial because all file references need to be relative, environment must be completely controlled and independent from any specific file system.
  2. Technology: Maven is a simple core concept that is activated through IoC container (Plexus). Everything is done in maven through plugins and every plugin works in isolation (ClassLoader). Plugings are downloaded from a plugin-repository on demand.

Maven’s Objectives:
The primary goal of maven is to allow the developers to comprehend the complete state of a project in the shortest time by using easy build process, uniform building system, quality project management information (such as change Log, cross-reference, mailing lists, dependencies, unit test reports, test coverage reports and many more), guidelines for best practices and transparent migration to new features. To achieve to this goal Maven attempts to deal with several areas like:

  • It makes the build process easy
  • Provides a uniform building system
  • Provides quality related project information
  • Provides guidelines related to development to meet the best goal.
  • Allows transparent migration to new features.

Introduction to Maven 2.0

Maven2 is an Open Source build tool that made the revolution in the area of building projects. Like the build systems as “make” and “ant” it is not a language to combine the build components but it is a build lifecycle framework. A development team does not require much time to automate the project’s build infrastructure since maven uses a standard directory layout and a default build lifecycle. Different development teams, under a common roof can set-up the way to work as standards in a very short time. This results in the automated build infrastructure in more stable state. On the other hand, since most of the setups are simple and reusable immediately in all the projects using maven therefore many important reports, checks, build and test animation are added to all the projects. Which was not possible without maven because of the heavy cost of every project setup.

Maven 2.0 was first released on 19 October 2005 and it is not backward compatible with the plugins and the projects of maven1. In December 2005, a lot of plugins were added to maven but not all plugins that exists for maven1 are ported yet. Maven 2 is expected to stabilize quickly with most of the Open Source technologies. People are introduced to use maven as the core build system for Java development in one project and a multi-project environment. After a little knowledge about the maven, developers are able to setup a new project with maven and also become aware of the default maven project structure. Developers are easily enabled to configure maven and its plugins for a project. Developers enable common settings for maven and its plugins over multiple projects, how to generate, distribute and deploy products and reports with maven so that they can use repositories to set up a company repository. Developers can also know about the most important plugins about how to install, configure and use them, just to look for other plugins to evaluate them so that they can be integrated in their work environment.

Maven is the standard way to build projects and it also provides various other characters like clearing the definition of the project, ways to share jars across projects. It also provides the easy way to publish project information (OOS).
Originally maven was designed to simplify the building processes in the Jakarta Turbine project. Several projects were there containing their own slightly different Ant build files and JARs were checked into CVS. An apache group’s tool that can build the projects, publish project information, defines what the project consists of and that can share JARs across several projects. The result of all these requirement was the maven tool that builds and manages the java-based-project.

Why maven is a great build tool? how does it differ from other Build tools?
Tell me more about Profiles and Nodes in Maven?
Tell me more about local repositories?
How did you configured local repositories in different environment (Development, Testing , Production etc)?
What is Transcend Dependencies in maven 2?
Did you write plugins in maven? if so what are they?
Why a matrix report is required during a new release?  How does this benefit QA Team?
What are pre-scripts and post-scripts in maven? Illustrate with an example?
What are the checklists for artifacts ? and what are the checklists for source code artifact?
Tell me the experience about Static Analysis Code?

Reference:
http://www.javabeat.net

Tagged : / / / / / / / / / / / / / / / / /

Interview Questions & Answer Sets : Shell Programming

shell-programming-interview

Interview Questions Sets : Shell Programming

How do you find out what’s your shell?
Answer: echo $SHELL

What’s the command to find out today’s date?
Answer: date

 What’s the command to find out users on the system?
Answer: who

How do you find out the current directory you’re in?
Answer: pwd

How do you remove a file?
Answer: rm

How do you remove a file?
Answer: rm -rf

How do you find out your own username?
Answer: whoami

How do you send a mail message to somebody?
Answer: mail somebody@techinterviews.com -s ‘Your subject’ -c ‘cc@techinterviews.com‘

How do you count words, lines and characters in a file?
Answer: wc

How do you search for a string inside a given file?
Answer: grep string filename

How do you search for a string inside a directory?
Answer: grep string *

How do you search for a string in a directory with the subdirectories recursed?
Answer: grep -r string *

What are PIDs?
Answer: They are process IDs given to processes. A PID can vary from 0 to 65535.

How do you list currently running process?
Answer: ps

How do you stop a process?
Answer: kill pid

How do you find out about all running processes?
Answer: ps -ag

How do you stop all the processes, except the shell window?
Answer: kill 0

How do you fire a process in the background?
Answer: ./process-name &

How do you refer to the arguments passed to a shell script?
Answer: $1, $2 and so on. $0 is your script name.

What’s the conditional statement in shell scripting?
Answer: if {condition} then … fi

How do you do number comparison in shell scripts?
Answer: -eq, -ne, -lt, -le, -gt, -ge

How do you test for file properties in shell scripts?
Answer: -s filename tells you if the file is not empty, -f filename tells you whether the argument is a file, and not a directory, -d filename tests if the argument is a directory, and not a file, -w filename tests for writeability, -r filename tests for readability, -x filename tests for executability

How do you do Boolean logic operators in shell scripting?
Answer: ! tests for logical not, -a tests for logical and, and -o tests for logical or.

How do you find out the number of arguments passed to the shell script?
Answer: $#

What’s a way to do multilevel if-else’s in shell scripting?
Answer: if {condition} then {statement} elif {condition} {statement} fi

How do you write a for loop in shell?
Answer: for {variable name} in {list} do {statement} done

How do you write a while loop in shell?
Answer: while {condition} do {statement} done

How does a case statement look in shell scripts?
Answer: case {variable} in {possible-value-1}) {statement};; {possible-value-2}) {statement};; esac

How do you read keyboard input in shell scripts?
Answer: read {variable-name}

How do you define a function in a shell script?
Answer: function-name() { #some code here return }

How does getopts command work?
Answer: The parameters to your script can be passed as -n 15 -x 20. Inside the script, you can iterate through the getopts array as while getopts n:x option, and the variable $option contains the value of the entered option.

What’s a way to do multilevel if-else’s in shell scripting?
Answer: if then elif fi

How do you write a for loop in shell?
Answer: for in do done

How do you write a while loop in shell?
Answer: while do done

How does a case statement look in shell scripts?
Answer: case in ) ;; ) ;; esac

How do you define a function in a shell script?
Answer: function-name()

How do you find out about all running processes?
Answer: ps -ag

How do you stop a process?
Answer: kill pid

How do you remove a file?
Answer: rm

How do you remove recursively?
Answer: rm -rf

What are PIDs?
Answer: They are process IDs given to processes. A PID can vary…

How do you list currently running process?
Answer: ps

What is $$?

What is a named pipe?

What does || mean?

What does && mean?

What is a loop?

What does while do?

What is a function?

What are the different kinds of loops available in shell script?
for if while case

What does $# stand for?

$# returns the number of parameters that are passed to a shell script
$? returns the exit code of the last executed command (0 : Successful, 1 or other: Failed)

What does $? return?
Will return the status of the command which is executed lastly.
0 > Success
2 > Error

How do u open a read only file in Unix?
“vi -R filename”

What is the difference between a shell variable that is exported and the one that is not exported?

If you have a string “one two three”, Which shell command would you use to extract the strings?

How do you schedule a command to run at 4:00 every morning?

How will you list only the empty lines in a file (using grep)?
grep ^$ filename.txt

When you login to a c shell, which script would be run first? (before the terminal is ready for the user)

first /etc/.login script is run & after that
~/.login is run & then ~/.cshrc is run.

How would you get the character positions 10-20 from a text file?
cat filename.txt | cut -c 10-20

How would you print just the 25th line in a file (smallest possible script please)?
tail -n +25Â | head -1 OR
head -n 25 | tail -1

How would you replace the n character in a file with some xyz?
sed ‘s/n/xyz/g’ filename > new_filename

Grep | SED |

How you will list the ordinary files in your current directory that are not user-writable?

Use Command substitution with grep to list the names of the persons from emp.lst who were born today.

How will you remove blank lines from a file using (i) grep  and (ii) sed?

Locate lines longer than 100 abd smaller than 150 characters using (i) grep  and (ii) sed?

How do you delete all leading and trailing spaces in all lines of a file?

Making Script Interactive
# read name
# echo “$name”

Special Parameters Used by Shell
# $* – It stores the complete set of positional parameters as a single string
# $? – Exit Status of last command
# $# – Number of arguments specified in command line
# $0 – Holds the command name itself
# $$ – PID of current Shell
# $! – PID of last the last Background job

Exit status of command
# exit 0 – Used when everything went fine
# exit 1 – Used when something went wrong

0 indicates the success and other values point to failure

The Logical Operator && and ||
cmd1 && cmd2 – cmd2 is excuted only when cmd1 succeeds.
cmd1 || cmd2 – cmd2 is excuted only when cmd1 Fails

Usage of –a and -o

The if Conditional
If command is successful
then
execute command
else
execute command
fi

If command is successful
then
execute command
fi

If command is successful
then
execute command
elif command is successful
then
execute command
else
execute command
fi

Using test AND [ ] to evaluate expressions
# test $x –eq $y
# [$x –eq $y]

Numeric Comparison Operators used by test
# -eq – Equal to
# -ne – Not Equal to
# -gt – Greater than
# -ge – Greater than or equal to
# -ge – Less than
# -le – Less than or equal to

String Tests used by test

Test True if
s1=s2 String s1 = s2
s1 != s2 String s1 is not equal to s2
-n stg String stg is not a null string
-z stg String stg is a null string
stg String stg is assigned and not null
s1 == s2 String s1 =s2

File related Tests with test

Test True if
-f file file exists and is a regular file
-r file file exists and is a readable
-w file file exists and is a writeable
-x file file exists and is a executable
-d file file exists and is a dirctory
-s file file exists and has a size greate than ero
-e file file exists
-u file file exists and has  SUID bit set
-L file file exists and is a Symbolic link

The case CONDITIONAL
read choice
case “$choice” in

  • ls –l ;;
  • ps –f ;;
  • date ;;
  • who ;;
  • exit ;;

*)   echo “Invalid options”
esac

for
for variable in list
do
commands
done

for file in *.htm *.html
do
sed ‘s/strong/STONG/g’ $file >> $$
mv $$ $file
gzip $file
done

while

while consition is true
do
commands
done

basename – Changing Filename Extension
# basename /home/henry/project3/dec2bin.pl
#dec2bin.pl
# basename ux2nd.txt txt
# ux2nd.                              – txt stripped off

set  AND shift – Manupulating the Positional Parameters
# set 9876 2345 6213
# echo “\$1 is $1, \$2 is $2, \$3 is $3”
# $1 is 9876, $2 is 2346, $3 is 6213

# set `date`
# echo $*

Note- set parses its arguments on the delimiters specified in the environment variable IFS which by default is whitespace.

Shift – Shifting arguments left

Maximum number of Bash arguments
On a 32-bit Linux, this is ARGMAX/4-1 (32767). This becomes relevant if the average length of arguments is smaller than 4.
Linux 2.6.23, one argument must not be longer than MAX_ARG_STRLEN (131072).

How to find success/failure status of a command in different shells?
echo $?
List all the users in Linux
cat /etc/passwd | cut -d”:” -f1

How to change the permission of multiple files which has 655 to 755
for myfile in `find . -perm 655`
do
chmod 755 $myfile
done

Shell script to Print only Size and file name using unix command
ls -l | tr -s ” ” ” “| cut -d ” ” -f5,9

Shell script to read file line by line
http://www.scmgalaxy.com/forum/shell-script/shell-script-to-read-file-line-by-line.html

How do you remove blank line using grep and sed in shell scripting?
# grep -v “^$” filename > newfilename
# sed ‘/^$/d’ /tmp/data.txt > /tmp/output.txt
# sed ‘/^[PRESS TAB]*$/d’ filename

List all the Groups and users in linux
# less /etc/passwd
# less /etc/group

How Do I Find Out CPU is 32bit or 64bit?

# grep flags /proc/cpuinfo
# uname

How to gunzip and untar all at once!
gunzip myfile.tar.gz
tar -xvf myfile.tar
into one
tar -zxvf myfile.tar.gz

Another way to kill multiple processes easily is by adding the following two functions to the .bash_profile.
function psgrep ()
{
ps aux | grep “$1” | grep -v ‘grep’
}

function psterm ()
{
[ ${#} -eq 0 ] && echo “usage: $FUNCNAME STRING” && return 0
local pid
pid=$(ps ax | grep “$1” | grep -v grep | awk ‘{ print $1 }’)
echo -e “terminating ‘$1’ / process(es):\n$pid”
kill -SIGTERM $pid
}

  # psgrep http

USER       PID %CPU %MEM    VSZ    RSS TTY  STAT START  TIME COMMAND
apache   31186       0.0        1.6  23736 17556 ?        S          Jul26       0:40  /usr/local/apache2/bin/httpd
apache   31187       0.0        1.3  20640 14444 ?        S          Jul26       0:37  /usr/local/apache2/bin/httpd

# psterm httpd

terminating 'httpd' / process(es):
31186
31187


Tagged : / / / / / / / / / / / / / / / /