Chef configuration management interview questions and answers | Chef Interview Q&A

chef-interview-questions-and-answers

Source – learn.chef.io

What is a resource?
Answer- A resource represents a piece of infrastructure and its desired state, such as a package that should be installed, a service that should be running, or a file that should be generated.

Question: What is a recipe?
Answer- A recipe is a collection of resources that describes a particular configuration or policy. A recipe describes everything that is required to configure part of a system. Recipes do things such as:

install and configure software components.
manage files.
deploy applications.
execute other recipes.

Question: What happens when you don’t specify a resource’s action?
Answer- When you don’t specify a resource’s action, Chef applies the default action.

Question: Are these two recipes the same?

package 'httpd'
service 'httpd' do    action [:enable, :start]  end

&&

service 'httpd' do    action [:enable, :start]    end
package 'httpd'

Answer-
No, they are not. Remember that Chef applies resources in the order they appear. So the first recipe ensures that the httpd package is installed and then configures the service. The second recipe configures the service and then ensures the package is installed.

Question: The second recipe may not work as you’d expect because the service resource will fail if the package is not yet installed.

Are these two recipes the same?

package 'httpd'
service 'httpd' do    action [:enable, :start]    end
package 'httpd'
service 'httpd' do    action [:start, :enable]    end

Answer-
No, they are not. Although both recipes ensure that the httpd package is installed before configuring its service, the first recipe enables the service when the system boots and then starts it. The second recipe starts the service and then enables it to start on reboot.

Are these two recipes the same?

file ‘/etc/motd’ do
owner ‘root’
group ‘root’
mode ‘0755’
action :create
end

file ‘/etc/motd’ do
action :create
mode ‘0755’
group ‘root’
owner ‘root’
end

Answer-
Yes, they are! Order matters with a lot of things in Chef, but you can order resource attributes any way you want.

Question –
Write a service resource that stops and then disables the httpd service from starting when the system boots.

Answer –
service ‘httpd’ do
action [:stop, :disable]
end

How does a cookbook differ from a recipe?
A recipe is a collection of resources, and typically configures a software package or some piece of infrastructure. A cookbook groups together recipes and other information in a way that is more manageable than having just recipes alone.

For example, in this lesson you used a template resource to manage your HTML home page from an external file. The recipe stated the configuration policy for your web site, and the template file contained the data. You used a cookbook to package both parts up into a single unit that you can later deploy.

How does chef-apply differ from chef-client?

chef-apply applies a single recipe; chef-client applies a cookbook.

For learning purposes, we had you start off with chef-apply because it helps you understand the basics quickly. In practice, chef-apply is useful when you want to quickly test something out. But for production purposes, you typically run chef-client to apply one or more cookbooks.

You’ll learn in the next module how to run chef-client remotely from your workstation.

What’s the run-list?

The run-list lets you specify which recipes to run, and the order in which to run them. The run-list is important for when you have multiple cookbooks, and the order in which they run matters.

What are the two ways to set up a Chef server?

Install an instance on your own infrastructure.
Use hosted Chef.

What’s the role of the Starter Kit?
The Starter Kit provides certificates and other files that enable you to securely communicate with the Chef server.

Where can you get reusable cookbooks that are written and maintained by the Chef community?
Chef Supermarket, https://supermarket.chef.io.

What’s the command that enables you to interact with the Chef server?
knife

What is a node?
A node represents a server and is typically a virtual machine, container instance, or physical server – basically any compute resource in your infrastructure that’s managed by Chef.

What information do you need to in order to bootstrap?
You need:

your node’s host name or public IP address.
a user name and password you can log on to your node with.
Alternatively, you can use key-based authentication instead of providing a user name and password.

What happens during the bootstrap process?
During the bootstrap process, the node downloads and installs chef-client, registers itself with the Chef server, and does an initial checkin. During this checkin, the node applies any cookbooks that are part of its run-list.

Which of the following lets you verify that your node has successfully bootstrapped?

The Chef management console.
knife node list
knife node show
You can use all three of these methods.

What is the command you use to upload a cookbook to the Chef server?
knife cookbook upload

How do you apply an updated cookbook to your node?
We mentioned two ways.

Run knife ssh from your workstation.
SSH directly into your server and run chef-client.
You can also run chef-client as a daemon, or service, to check in with the Chef server on a regular interval, say every 15 or 30 minutes.

Update your Apache cookbook to display your node’s host name, platform, total installed memory, and number of CPUs in addition to its FQDN on the home page.

Update index.html.erb like this.
<html>
<body>
<h1>hello from <%= node[‘fqdn’] %></h1>

<pre>
<%= node[‘hostname’] %>
<%= node[‘platform’] %> – <%= node[‘platform_version’] %>
<%= node[‘memory’][‘total’] %> RAM
<%= node[‘cpu’][‘total’] %> CPUs
</pre>
</body>
</html>

Then upload your cookbook and run it on your node.

What would you set your cookbook’s version to once it’s ready to use in production?

According to Semantic Versioning, you should set your cookbook’s version number to 1.0.0 at the point it’s ready to use in production.

What is the latest version of the haproxy community cookbook?

To know the latest version of any cookbook on Chef Supermarket, browse to its page and view the latest version from the version selection box.

Or, get the info from the knife cookbook site command, like this.

knife cookbook site show haproxy | grep latest_version
latest_version: http://cookbooks.opscode.com/api/v1/cookbooks/haproxy/versions/1.6.6

Create a second node and apply the awesome_customers cookbook to it. How long does it take?

You already accomplished the majority of the tasks that you need. You wrote the awesome_customers cookbook, uploaded it and its dependent cookbooks to the Chef server, applied the awesome_customers cookbook to your node, and verified that everything’s working.

All you need to do now is:

Bring up a second Red Hat Enterprise Linux or CentOS node.
Copy your secret key file to your second node.
Bootstrap your node the same way as before. Because you include the awesome_customers cookbook in your run-list, your node will apply that cookbook during the bootstrap process.
The result is a second node that’s configured identically to the first one. The process should take far less time because you already did most of the work.

Now when you fix an issue or add a new feature, you’ll be able to deploy and verify your update much more quickly!

What’s the value of local development using Test Kitchen?

Local development with Test Kitchen:

enables you to use a variety of virtualization providers that create virtual machine or container instances locally on your workstation or in the cloud.
enables you to run your cookbooks on servers that resemble those that you use in production.
speeds up the development cycle by automatically provisioning and tearing down temporary instances, resolving cookbook dependencies, and applying your cookbooks to your instances.

What is VirtualBox? What is Vagrant?

VirtualBox is the software that manages your virtual machine instances.

Vagrant helps Test Kitchen communicate with VirtualBox and configures things like available memory and network settings.

Verify that your motd cookbook runs on both CentOS 6.6 and CentOS 6.5.

Your motd cookbook is already configured to work on CentOS 6.6 as well as CentOS 6.5, so you don’t need to modify it.

To run it on CentOS 6.5, add an entry to the platforms section of your .kitchen.yml file like this.

---       driver:       name: vagrant
provisioner:       name: chef_zero
platforms:       - name: centos-6.6       driver:       box: opscode-centos-6.6       box_url: http://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_centos-6.6_chef-provisionerless.box       - name: centos-6.5       driver:       box: opscode-centos-6.5       box_url: http://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_centos-6.5_chef-provisionerless.box
suites:       - name: default       run_list:       - recipe[motd::default]       attributes:

In many cases, Test Kitchen can infer the box and box_url parameters, which specify the name and location of the base image, or box. We specify them here to show you how to use them.

Run kitchen list to see the matrix of test instances that are available. Here, we have two platforms – CentOS 6.5 and CentOS 6.6 – multiplied by one suite – default.

$kitchen list

Instance           Driver   Provisioner  Verifier  Transport  Last Action default-centos-66  Vagrant  ChefZero     Busser    Ssh        <Not Created> default-centos-65  Vagrant  ChefZero     Busser    Ssh        <Not Created>

Run kitchen converge to create the instances and apply the motd cookbook.

$kitchen converge    -----> Starting Kitchen (v1.4.0)    -----> Creating <default-centos-66>...    Bringing machine 'default' up with 'virtualbox' provider...    [...]    Running handlers:    Running handlers complete    Chef Client finished, 1/1 resources updated in 10.372334751 seconds    Finished converging <default-centos-66> (3m52.59s).    -----> Creating <default-centos-65>...    Bringing machine 'default' up with 'virtualbox' provider...    [...]    Running handlers:    Running handlers complete    Chef Client finished, 1/1 resources updated in 5.32753132 seconds    Finished converging <default-centos-65> (10m12.63s).  -----> Kitchen is finished. (19m47.71s)

Now to confirm that everything’s working, run kitchen login. But this time, you need to provide the instance name so that Test Kitchen knows which instance to connect to.

$kitchen login default-centos-66       Last login: Wed May 13 20:15:00 2015 from 10.0.2.2              hostname:  default-centos-66       fqdn:      default-centos-66       memory:    469392kB       cpu count: 1       [vagrant@default-centos-66 ~]$ logout       Connection to 127.0.0.1 closed.$kitchen login default-centos-65       Last login: Wed May 13 20:28:18 2015 from 10.0.2.2              hostname:  default-centos-65       fqdn:      default-centos-65       memory:    469452kB       cpu count: 1       [vagrant@default-centos-65 ~]$ logout       Connection to 127.0.0.1 closed.
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 : / / / / / / / / / / / / / / /

Top Interview Questions and Answers of Jenkins

jenkins-interview-questions

  • What is continuous integration?

  • Jenkins Continuous integration API features?

  • Advantages of jenkins?

  • Jenkins plugins?

  • Requirements for using Jenkins?

  • Installing Jenkins on Ubuntu and RHEL?

  • Process to take Jenkins backup and copying files?

  • Top 20 Jenkins and Useful Plugins?

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

Top 10 Interview Questions and Answers in SVN (Subversion)

svn-subversion-interview-questions-and-answers

  • What is SVN?

  • What is “branch” , “Tag” and “Trunk” in SVN ?

  • what do you mean by “Synchronizing with Repository” ? How is it different from “Update” ?

  • Difference between Update and Commit ?

  • How to apply a patch in SVN ?

  • What if SVN Update gives Merge Conflicts and you just want your local files to be overriden with the repository versions ?

  • trunk vs branch vs tag in subversion or SVN

  • What is the process to take backuop and restore in SVN?

  • How to setup SVN?

  • How to setup authentication in SVN?

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

All Possible Interview Questions on Git, Github and Gitlab

interview-questions-on-git-github-gitlab

  • What is GIT?
  • What is a repository in GIT?
  • What is the command you can use to write a commit message?
  • What is the difference between GIT and SVN and other CM systems?
    • Answers –
      • Cheap Local Branching
      • Everything is Local
      • Git is Fast
      • Git is Small
      • The Staging Area
      • Distributed
      • Any Workflow
      • Easy to Learn
      • Git is the new standard
  • What are the advantages of using GIT?
  • What language is used in GIT?
  • What is the function of ‘GIT PUSH’ in GIT?
  • Why GIT better than Subversion?
  • What is “Staging Area” or “Index” in GIT?
  • What is GIT stash?
  • What is GIT stash drop?
  • How will you know in GIT if a branch has been already merged into master?
  • What is the function of git clone?
  • What is the function of ‘git config’?
  • What does commit object contain?
  • How can you create a repository in Git?
  • What is ‘head’ in git and how many heads can be created in a repository?
  • What is the purpose of branching in GIT?
  • What is the common branching pattern in GIT?
  • How can you bring a new feature in the main branch?
  • What is a ‘conflict’ in git?
  • How can conflict in git resolved?
  • To delete a branch what is the command that is used?
  • What is another option for merging in git?
  • What is the syntax for “Rebasing” in Git?
  • What is the difference between ‘git remote’ and ‘git clone’?
  • What is GIT version control?
  • Mention some of the best graphical GIT client for LINUX?
  • What is Subgit? Why to use Subgit?
  • What is the function of ‘git diff ’ in git?
  • What is ‘git status’ is used for?
  • What is the difference between the ‘git diff ’and ‘git status’?
  • What is the function of ‘git checkout’ in git?
  • What is the function of ‘git rm’?
  • What is the function of ‘git stash apply’?
  • What is the use of ‘git log’?
  • What is ‘git add’ is used for?
  • What is the function of ‘git reset’?
  • What is git Is-tree?
  • How git instaweb is used?
  • What does ‘hooks’ consist of in git?
  • Explain what is commit message?
  • How can you fix a broken commit?
  • What is ‘bare repository’ in GIT?
  • How do you start Git and what is the process called?
  • How do you put your local repository (repo) on the GitHub server?
  • How to delete the working branch?
  • What as the strength and weaknesses of the software?
  • But I am quite happy with Subversion (SVN). What is all this fuss about? Is there a substantial trend for distributed versioning control systems (DVCS)?
  • Isn’t DVCS something for small teams and startups? I am working in a very big company. We value established things way more than the cutting edge stuff, that may not be here to stay.
  • Okay. Let’s say we go with DVCS. Why should I take git and not mercurial?
  • I like, that git allows our developers to host the complete repository on his local machine. That makes software development faster. So why do
  • you I need Stash on top?
  • How do you use this rights management with Stash? How does it work? Will developers only get have a repository? Is that still functional then?
  • What is a pull request? What is this for? Aren’t we sharing all code with all developers and let everyone do what he wants? Is that only for
  • hierachical software development methods?
  • How would you summarize the advantages of Stash in short?
  • What is the one reason, that your customers give Atlassian today on why they purchase Stash?
  • Can you offer us a small sneak peak into your upcoming next releases? Is there anything, that you can share first hand with us?
  • What is your general roadmap for stash? Where do you want to position it near and long term?
  • Do you ultimately plan to support Mercurial? When is a good time to buy Stash, if I run with hg at the moment?
  • Why should I go for Stash in favor of GitHub Enterprise or RhodeCode?
  • Why is Stash a separated product and not part of Bitbucket. I could imagine seeing Bitbucket Enterprise resembling GitHub Enterprise.
  • Is Atlassian using Stash internally in software development? If not, why not?
  • Wouldn’t it be interesting to combine Fisheye, Crucible and Stash in one product?
  • What is the difference between GIT and SVN?
  • What are the advantages of using GIT over other tools?
  • What is GIT stash?
  • What does commit object contain?
  • How can conflict in git resolved?
  • What is the difference between ‘git remote’ and ‘git clone’?
  • Mention some of the best graphical GIT client for LINUX?
  • What does ‘hooks’ consist of in git?
  • What is ‘bare repository’ in GIT?
  • Add a line to the some.txt file and then throw out all changes since the last commit.
  • Why GIT better than Subversion?
  • How to troubleshoot Git?
  • How to troubleshoot GitLab?
  • How to troubleshoot Github?
  • How to take Gitlab backup
  • What is Git Objects? explain about Tree, blob, commit, tag, branch objects?
  • How git Object storage works?
  • What is SHA1?
  • Introduction to the GitHub platform
  • github Distributed version control synchronization
  • github Project management and repository integration
  • github Multiple remotes and Fork maintenance
  • github Remote repository interaction and dependencies
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 : / / / / / / / / / / / / / / /

Selected AnthillPro Interview Questions

anthillpro-interview-questions

Selected AnthillPro Interview Questions

  • Building Procedures in AnthillPro
  • Deploying Procedures with AnthillPro
  • Using AnthillPro for Audit
  • Process of Integrating with Defect & Feature Tracking
  • Process of Integrating with Static Code Analysis
Tagged : / / / / / / / / / / / / / / / /

Top Selected Bamboo Interview Questions

bamboo-interview-questions

Top Selected Bamboo Interview Questions

Bamboo Questions:

  1. Tell me more about continuous integration ? How did you configured?
  2. Plugins used in Bamboo?
  3. Tell me more about Bamboo Schedule Options?
  4. How did you configured Bamboo with Subversion?

 

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 : / / / / / / / / / / / / / / / /