Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Perl arrays are a really simple way of implementing stacks and related data structures. The key is to realise that you can access the ends of the array using [0] for the left/bottom/start of the array and [-1] for the right/top/end of the array.

With that in mind you can either use unshift/shift to add/remove items at the start, or push/pop to add/remove things at the end of the array and implement a stack. The following pushes an item onto a stack, accesses it (at the top of the stack), then pops it off again:

my @stack; push @stack, "An item to push on the stack"; print "The top stack item is: $stack[-1]\n"; pop @stack;

Using unshift/shift/[0] gives stack semantics as does push/pop/[-1].

Using push/shift/[0] or unshift/pop/[-1] gives queue semantics.

push/pop/shift/unshift will return undef if the stack/queue was empty. If you may be intentionally placing undef values in the stack, you can still check if it is empty: scalar(@stack) returns the number of elements on the stack.

By combining these and adding splice to the mix you can do some really nifty stuff that combine stack, list and queue sematics in one data structure.

For info on splice see How do I insert an element into an arbitrary (in range) array index? and How do I completely remove an element from an array?.

In reply to Re: How do I make a stack? by GrandFather
in thread How do I make a stack? by GrandFather

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-04-22 12:44 GMT
Find Nodes?
    Voting Booth?

    No recent polls found